6

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?

Stefan
  • 1,041
  • 1
  • 14
  • 28

1 Answers1

16

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 :)
});
raubas
  • 674
  • 7
  • 6