猫鼬和诺言:如何获取查询结果数组? [英] Mongoose and promises: how to get an array of query results?

查看:94
本文介绍了猫鼬和诺言:如何获取查询结果数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用猫鼬从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆