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!
A MongoDB Stored Procedure is a simple Javascript function that is saved in a special collection labeled as db. system. js. Remember, if the mongod command is not running in the terminal, install it now.
MongoDB supports JavaScript through the official Node. js driver. You can connect your Node. js applications to MongoDB and work with your data.
The MongoDB shell is an interactive JavaScript shell. As such, it provides the capability to use JavaScript code directly in the shell or executed as a standalone JavaScript file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With