K-2052
K-2052

Reputation: 197

storing a mongoose (node.js orm) query result

Is there anyway to do something like:

var first_user = User.find({ _id: user_id }).first(); 

using the mongoose ORM? http://github.com/LearnBoost/mongoose

What I'm trying to do is to store the returned result of the query for later use.

When I use the above, all I get returned into the var first_user is the QueryWriter object.

Upvotes: 2

Views: 3900

Answers (1)

bxjx
bxjx

Reputation: 1838

You can access the results of a mongoose query through a passed callback. You'll find that mongoose, like most node.js modules, makes extensive use of async callbacks. Mongoose also provides a nice method for returning an object by its id, and if you want to use this result outside of the scope of the callback, you can do it like this:

var first_user;
User.findById(user_id, function(user){
  first_user = user;
});

For other mongoose API calls, I recommend looking at the mongoose tests for a good reference. Check out http://github.com/LearnBoost/mongoose/blob/master/tests/integration/model.test.js

Upvotes: 3

Related Questions