aggregate returns empty array - mongoose

跟風遠走 提交于 2019-12-11 03:25:56

问题


I have the following two simple queries:

Comment.aggregate([{$match: { _id: req.params.id }}])
  .exec(function(err, result) {
    // result is empty
  });

Comment.find({ _id: req.params.id })
  .exec(function (err, result) {
    // correct result returned
  });

My problem is, that the aggregate-Function returns an empty array. Aren't they supposed to return the same result?


回答1:


Yes, but you need to cast the id (which is a string) to an objectID :)

let idToSearch = mongoose.Types.ObjectId(req.params.id)
Comment.aggregate([{$match: { _id: idToSearch }}])
.exec(function(err, result) {
    // result is now correct :)
});


来源:https://stackoverflow.com/questions/40636434/aggregate-returns-empty-array-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!