Mongoose和promises:如何获得一系列查询结果?

11 mongoose mongodb node.js promise q

使用mongoose来查询db和Q for promises的结果,但是发现很难找到一个可用的用户列表.目前我有这样的事情:

var checkForPerson = function( person ) {
    people = mongoose.model('Person', Person)

    return people.findOne({"_id": person }, function(err, doc) {
        if (err) console.log(err)

        if (doc !== null) {
            return doc
        } else { 
            console.log('no results')
        }

    })
}

var promises = someArrayOfIds.map(checkForPerson);

// this is where I would like to have an array of models
var users = Q.all(promises)

//this fires off before the people.findOne query above to users is undefined
SomeOtherFunction( users )
Run Code Online (Sandbox Code Playgroud)

如果SomeOtherFunction没有做大量的草率回调,我将如何完成查询?

Wir*_*rie 19

另一个建议是使用MongoDB的$in运算符传入一个数组find并有效地获得大量结果.每个都是一个Mongoose对象.

var promise = people.find({ _id: { $in: someArrayOfIds }).exec();
promise.then(function(arrayOfPeople) {
  // array of people ... do what you want here...
});
Run Code Online (Sandbox Code Playgroud)

这比制作多个请求(每个请求一个)要高效得多_id.


Ben*_*aum 5

"如何继续承诺"这个问题的答案几乎总是如此.then.这是承诺的类比,;它终止了一个异步语句.您可以在其中返回承诺,并在继续之前将其解包.

Q.all(promises).then(function(users){
    SomeOtherFunction(users);
});
Run Code Online (Sandbox Code Playgroud)

或者干脆 Q.all(promise).then(SomeOtherFunction)

你还需要findOne来实际返回promises.您可以使用Q.nfcall哪个调用节点函数或自己实现它.

什么Q.all是接受一系列的承诺和满足当所有这些做和拒绝时,其中一个拒绝.您可能希望.catch在任何查询失败或使用时附加处理程序.done以表示链的结尾.其他承诺库如Bluebird即使没有.done或添加显式处理程序也会为您拾取错误,遗憾的是Q不会这样做.

  • 仅供参考:`findOne().exec()`返回一个Promise. (4认同)
  • @WiredPrairie在这种情况下 - OP肯定应该使用`findOne(..).exec`而不是打扰nfcall或手动宣传它.OP - 还要注意这意味着你不需要所有`.if(错误)的东西,承诺会照顾你. (2认同)