onkkno
onkkno

Reputation: 709

Mongoose/MongoDB - How to use promise with aggregate queries

I am trying to perform 2 queries to 2 different collections in MongoDB via mongoose and then combine their results for a REST API response.

Example:

var result1 = Model1.aggregate([<operations here>]).exec()

var result2 = Model2.aggregate([<operations here>]).exec()

var allDone = Promise.all(result1,result2)

allDone.then(function(data1,data2){
//Do something with both data
})

I get this error TypeError: Cannot read property 'readPreference' of undefined

Which used to happen when the function signature for the callback wasnt function(err,docs){...

If I use callbacks for Aggregators , it works but I didn't want to chain callbacks/the queries and thought this way would be more efficient.

I found this Mongoose aggregate cursor promise

But wanted to know if this is possible with native promises in a simpler way. I do not want to iterate through the cursor too as explained in the above SO answer.

Upvotes: 4

Views: 4545

Answers (1)

onkkno
onkkno

Reputation: 709

var allDone = Promise.all(result1,result2) 

should have been

var allDone = Promise.all([result1,result2])

Upvotes: 6

Related Questions