【问题标题】:How to wait for the result of a mongoose query?如何等待猫鼬查询的结果?
【发布时间】:2014-03-03 15:18:49
【问题描述】:

我尝试根据猫鼬查询的结果过滤数组。标准过滤器函数期望回调返回 true 或 false。我的麻烦是这些信息取决于猫鼬 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
});

【问题讨论】:

    标签: node.js mongoose


    【解决方案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.
    });
    

    【讨论】:

    • 我试过了,结果还是一样。问题没有解决。除了来自 async man 的示例之外,您还有其他示例吗?还是谢谢。
    • @niko 用您尝试过的方法更新您的问题,我应该能够帮助您解决问题。
    • RTFM !太感谢了!我不敢相信我花了 3 个小时在谷歌上搜索来解决这个问题!
    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 2018-08-09
    • 2016-08-16
    • 2017-05-08
    • 2017-10-30
    • 2018-11-29
    • 2015-11-28
    • 2012-10-28
    相关资源
    最近更新 更多