如何等待mongoose查询的结果?

时间:2014-02-06 15:25:22

标签: node.js mongoose

我尝试根据mongoose查询的结果过滤数组。标准过滤器函数期望回调返回true或false。我的麻烦是这个信息取决于mongoose findOne查询的异步结果

# 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

任何人都知道如何解决这类问题?

我也试过使用异步过滤功能,但我不认为它适用于我的情况(或者我可能不太了解)

以下是我对异步过滤器的理解以及为什么(我认为)它无法解决我的问题:

// 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
});

1 个答案:

答案 0 :(得分:1)

请改用async库中的filter功能。

<强>更新

你的尝试非常接近,你只需要将结果提供给回调而不是返回它:

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.
});