使用猫鼬从数据库和 Q 中查询结果以获取承诺,但发现很难只获取可用用户列表。目前我有一些这样的东西:
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 )
我将如何让查询在之前完成SomeOtherFunction
不做大量草率的回调?
另一个建议是使用 MongoDB$in
运算符将数组传递给find
并有效地获得大量结果。每个都是一个 Mongoose 对象。
var promise = people.find({ _id: { $in: someArrayOfIds }).exec();
promise.then(function(arrayOfPeople) {
// array of people ... do what you want here...
});
这比发出多个请求(每个请求一个)要高效得多_id
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)