Problems storing JS functions in Mongo DB using Node.js

I have a simple JS class:

var User = function(id){
    this._id = id;
    this.sayHello = function (){
        return "hello";
    }
}

Then I go to the repository in MongoDB using the default Node.js driver:

users.insert(new User(1));

Finally, I retrieve the user and try to execute the function:

users.findOne({_id:1}, function(err, item) {
    console.log("Say hello: " + item.sayHello());
});

I get the following error, which is really confusing:

    throw err;
          ^
TypeError: Object #<Object> has no method 'sayHello'

I completely lost it. I realized that MongoDB stores both JS functions and as-is properties. If this is not the case, can you recommend how I can get around this?

Thank!

+5
source share
1 answer

Mongo cannot store functions (code), only data. Take the raw data you will return and pass it to the constructor function, or consider ODM as mongoose.

, mongo . MongoDB. , , mongo, , , . node.js .js. .

+9

All Articles