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?

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.

By : Bookworm


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

By : bxjx

This video can help you solving your question :)
By: admin