Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Using lean on aggregate function

I'm trying to use the lean() option in order to speed up my queries. But when adding it to a query like this:

Pets.aggregate({ $match: { 'Name': 'Floofkins', 'lastMealDate': {$gt: today}}}, function (err, pets){
  if (err) {
    res.status(500).json({'error': err});
    console.log('Could not fetch pets: ' + err);
    return;
  }
    petsHadMealsToday = pets.length;
}).lean();

All I get is TypeError: Cannot read property 'lean' of undefined although pets.length returns the number of pets that matched the query.

If I'd remove the match option however and run something like below, it works like a charm.

Pets.aggregate({ 'Name': 'Floofkins', 'lastMealDate': {$gt: today}}, function (err, pets){
      if (err) {
        res.status(500).json({'error': err});
        console.log('Could not fetch pets: ' + err);
        return;
      }
        petsHadMealsToday = pets.length;
    }).lean();

I guess I'm missing some fundamental point about how to use match and such, so feel free to educate me!

like image 781
bork Avatar asked Dec 12 '17 08:12

bork


2 Answers

After reading a bit, this is my take on the answer to my question:

lean() is not needed on an aggregate function as the documents returned are plain JavaScript objects, and not Mongoose objects. This is because any shape of document can be returned. Source.

Therefore adding lean() to an aggregate function will generate an error since there is nothing to perform the lean() function upon.

like image 109
bork Avatar answered Oct 06 '22 23:10

bork


No need to lean pipeline output . Aggregate output is already lean , using mongoose too http://mongoosejs.com/docs/api.html#model_Model.aggregate

because output of aggregate pipeline is not a mongoose document

like image 38
Shubham Avatar answered Oct 07 '22 00:10

Shubham