libik
libik

Reputation: 23029

Mongoose aggregate method does not work

I have these lines :

            Score.find({gameId : gameId}).exec(function(err,obj){
                console.log("find length : " + obj.length);
            });

            Score.aggregate([
                {$match: {gameId: gameId}}
            ], function (err, result) {
                console.log('result is : ' + JSON.stringify(result));
                console.log('is there any error : ' + err);
            });

And output of these lines are

result is : []
is there any error : null
find length : 1

I do not understand, why "match" method of aggregate does not work as expected - finding all documents, that match properties. I added Score.find with same "body" to find out, if the document really exist and it does.

PS : {gameId: gameId} - first gameId is name of property, second one is string value with ID I am looking for.


PS2: fluent api having same result :

            Score.aggregate().match({gameId: gameId}).exec(function (err, result){
                console.log('result is : ' + JSON.stringify(result));
                console.log('is there any error : ' + err);
            });

Upvotes: 3

Views: 1870

Answers (2)

Naveen Kumar
Naveen Kumar

Reputation: 1067

Please try below code :

Collection.aggregate([
{
  $match: {
    cid: ObjectId(req.params.cid),
    createdAt: {
      $gte: new Date(req.query.startDate),
      $lt: new Date(req.query.endDate)
    }
  }
},
{
  $group: {
    _id: {
      day: {$dayOfMonth: "$createdAt"},
      month: {$month: "$createdAt"},
      year: {$year: "$createdAt"}
    },
    count: {$sum: 1}
  }
}
]).then(function (result) {
  return res.json(result);
}, function (error) {
  return res.status(500).send(error);
});

Upvotes: 1

styopdev
styopdev

Reputation: 2664

You should convert gameId string to mongodb ObjectId

in mongoose

mongoose.Types.ObjectId(gameId)

mongodb native way

new ObjectId(gameId)

Upvotes: 4

Related Questions