nlko
nlko

Reputation: 520

How to wait for the result of a mongoose query?

I try to filter an array according to the result of a mongoose query. The standard filter function expect the callback to return true or false. My trouble is that this information depends on the asynchronous result of a mongoose findOne query

# code that does not work
myArray.filter = (elem) ->
  MyCollection.findOne {_id : elem}, (err,elem) ->
    result = err==null
  #Need to wait here for the result to be set
  result

Anyone has a clue how to resolve that kind problem ?

I tried as well to use the async filter function but I don't think it works in my case (or I maybe I don't understand well)

Here is my understanding of async filter and why (I think) it can't solve my problem :

// code that doesn't work
async.filter(myArray, function(elem){
  var result = true;
  MyCollection.findOne({_id : elem}, function(err,elem) {
    result = err==null;
  });
  // the filter exits without waiting the update done asychronously in the findOne callback
  return result;
}, 
function(results){
  // results now equals an array of the existing files
});

Upvotes: 0

Views: 5436

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

Use the filter function from the async library instead.

UPDATE

You're pretty close in your attempt, you just need to provide the result to the callback instead of returning it:

async.filter(myArray, function(elem, callback){
  MyCollection.findOne({_id : elem}, function(err, doc) {
    callback(err == null && doc != null);
  });
}, 
function(results){
  // results is myArray filtered to just the elements where findOne found a doc
  // with a matching _id.
});

Upvotes: 2

Related Questions