Stefan Stefan - 1 year ago 112
Node.js Question

aggregate returns empty array - mongoose

I have the following two simple queries:

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

Comment.find({ _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?

Answer Source

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

let idToSearch = mongoose.Types.ObjectId(
Comment.aggregate([{$match: { _id: idToSearch }}])
.exec(function(err, result) {
    // result is now correct :)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download