猫鼬和诺言:如何获取查询结果数组? [英] Mongoose and promises: how to get an array of query results?
问题描述
使用猫鼬从db和Q查询结果以获取承诺,但发现仅获得可用的用户列表很难使我的头全神贯注.目前,我有一些类似的东西:
Using mongoose to query results from the db and Q for promises, but finding it hard to wrap my head around just getting a list of users that's available. Currently I have some something like this:
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
之前完成查询?
How would I go about having the queries finish before SomeOtherFunction
without doing tons of sloppy callbacks?
推荐答案
另一个建议是使用MongoDB的$in
运算符将数组传递给find
并有效地获取大量结果.每个对象都是猫鼬对象.
Another suggestion would be to use MongoDB's $in
operator to pass in an array to find
and get a large set of results efficiently. Each will be a Mongoose object.
var promise = people.find({ _id: { $in: someArrayOfIds }).exec();
promise.then(function(arrayOfPeople) {
// array of people ... do what you want here...
});
这比发出多个请求(每个_id
一个)的效率要高得多.
This would be far more efficient than making multiple requests, one for each _id
.
这篇关于猫鼬和诺言:如何获取查询结果数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!