0

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
});
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
nlko
  • 500
  • 1
  • 6
  • 9

1 Answers1

2

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.
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • I tried and it ended up to the same way. Problem not solved. Do you have an example other than the one from the async man ? Thank anyway. – nlko Feb 06 '14 at 18:36
  • @niko Update your question with what you tried and I should be able to help you get it working. – JohnnyHK Feb 06 '14 at 18:38
  • 1
    RTFM ! Thank you so much! I can't believe I spend 3 hours googling around to solve this! – nlko Feb 06 '14 at 20:09