I have a simple JS class:
var User = function(id){
this._id = id;
this.sayHello = function (){
return "hello";
}
}
I then go to store it 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 receive the following error, which is really confusing:
throw err;
^
TypeError: Object #<Object> has no method 'sayHello'
I'm totally lost on this one. My understanding was that MongoDB stored both JS functions and properties as-is. If this isn't the case, can you recommend how I can work around this?
Thanks!
Mongo cannot store functions (code), only data. Take the raw data you get back and pass it to a constructor function, or consider an ODM like mongoose.
There are a very specific and limited set of conditions wherein you can send mongo function code in string form and have it evaluated on the server. These are documented in the MongoDB manual. However, the purpose of that code running inside mongo is to support sophisticated data query operations, not to model application logic, which is what this question is asking about. Application logic goes in your node.js module .js files. Data goes in the database.