6

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!

3
  • your example is working for me via the mongo shell. No errors what so ever and sayHello() is invoked correctly too. Commented Mar 15, 2013 at 11:22
  • @zeusdeux the question is about 2 processes: mongodb and a separate node.js application server process. The mongo shell is a development utility. This question is about building an application in node.js. Commented Mar 15, 2013 at 15:27
  • @peter yes I got that bit. The object methods are serialized before storing anyway so in all probability the result should not differ irrespective of where it is performed from, be it the mongo client or a node app. I shall try it from within an app today just to be sure. Commented Mar 16, 2013 at 15:18

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree with the edit. Separate application logic and data that it works on. Send the data to mongodb and app logic in modules within your app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.