简体   繁体   English

Mongoose / MongoDB - 如何使用聚合查询的promise

[英]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. 我试图通过mongoose对MongoDB中的2个不同集合执行2个查询,然后将它们的结果组合成REST API响应。

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 我得到这个错误TypeError:无法读取未定义的属性'readPreference'

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. 如果我使用Aggregators的回调,它可以工作,但我不想链接回调/查询,并认为这样会更有效。

I found this Mongoose aggregate cursor promise 我发现这个Mongoose聚合游标承诺

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. 我也不想像上面的答案中所解释的那样迭代光标。

var allDone = Promise.all(result1,result2) 

本来应该

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM