MongoDB: Using lean on aggregate function

2020-07-13 09:00发布

问题:

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!

回答1:

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.



回答2:

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