TypeError:无法在node.js中调用未定义的方法“toArray”,而在aggregatein mongo中

在node.js中进行聚合时出现以下错误。

错误:TypeError:无法调用未定义的方法“toArray”

doctorsCollection.aggregate([ {$project:{"treatments._id":1, "treatments.price":1}}, {$unwind:"$treatments"}, {$match:{"treatments._id": parseInt(treatments[i])}}, {$sort:{"treatments.price":-1}}, {$limit:1} ]).toArray(function(err, result) { console.log(err); }); 

我不知道发生了什么事。 任何帮助,将不胜感激。 谢谢!

从node.js MongoDB驱动程序的.aggregate文档中,该方法不会返回游标,除非您指定将游标作为选项返回。 默认情况下,它将返回null所以.toArray方法不起作用/有意义。

有几种方法来处理它,文档提供了大量的例子。 在你的情况下,你可以添加{cursor: {batchSize: 1}}作为.aggregate的第二个参数,它将工作。