Mongoose/MongoDB—如何在聚合查询中使用承诺。

时间:2023-02-09 22:31:13

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个查询,然后结合它们的结果进行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

我得到了这个错误类型:无法读取未定义的属性“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.

如果我对聚合器使用回调,它可以工作,但我不想链回调/查询,这样就更有效了。

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.

但是想知道这是否可能,用一种更简单的方法来实现本机承诺。我不想重复遍历游标,如上面的SO answer所述。

1 个解决方案

#1


3  

var allDone = Promise.all(result1,result2) 

should have been

应该是

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

#1


3  

var allDone = Promise.all(result1,result2) 

should have been

应该是

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