MongoDB:使用精简聚合函数 [英] MongoDB: Using lean on aggregate function

查看:162
本文介绍了MongoDB:使用精简聚合函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用lean()选项以加快查询速度.但是,当将其添加到这样的查询中时:

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();

我得到的只是TypeError: Cannot read property 'lean' of undefined,尽管pets.length返回了与查询匹配的宠物数.

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

但是,如果我删除match选项并运行如下所示的内容,它的工作原理就像是一种魅力.

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();

我想我缺少有关如何使用match的基本知识,所以请随时教育我!

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

推荐答案

看了一点之后,这就是我对问题的答案:

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

lean(),因为返回的文档是纯JavaScript对象,而不是Mongoose对象.这是因为可以返回任何形状的文档. 来源.

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.

因此,将lean()添加到aggregate函数将产生错误,因为没有任何内容可以执行lean()函数.

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

这篇关于MongoDB:使用精简聚合函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆