Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aggregate returns empty array - mongoose

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?

like image 933
Stefan Avatar asked Jul 13 '26 07:07

Stefan


1 Answers

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 :)
});
like image 117
raubas Avatar answered Jul 16 '26 09:07

raubas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!