Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems storing JS functions in Mongo DB with Node.js

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!

like image 977
djcredo Avatar asked Mar 15 '13 01:03

djcredo


People also ask

Can we store function in MongoDB?

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.

Can I use JavaScript in MongoDB?

MongoDB supports JavaScript through the official Node. js driver. You can connect your Node. js applications to MongoDB and work with your data.

Can MongoDB manipulate JavaScript objects?

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.


1 Answers

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.

like image 190
Peter Lyons Avatar answered Oct 29 '22 14:10

Peter Lyons