views:

83

answers:

1

Hi,

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 store the returned result of the query for later use.

When I use the above all I get returned into the "first_user" var is the QueryWriter object. Hoping there is a knowledgeable Mongoose user out there who can help me.

A: 

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

bxjx
Thanks. It occurred to me after posting that my desired syntax, had it been available would by its nature block.
Bookworm
Exactly right! :)
bxjx