Mongoose and promises: how to get an array of query results?

user240993 picture user240993 · Apr 1, 2014 · Viewed 17.5k times · Source

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 )

How would I go about having the queries finish before SomeOtherFunction without doing tons of sloppy callbacks?

Answer

WiredPrairie picture WiredPrairie · Apr 1, 2014

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...
});

This would be far more efficient than making multiple requests, one for each _id.