我正在尝试使用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:使用精简聚合函数
发布评论