select vs find and where vs find in Mongoose



在Mongoose文档中有这样一小段代码:

Person
.find({ occupation: /host/ })
.where('name.last').equals('Ghost')
.where('age').gt(17).lt(66)
.where('likes').in(['vaporizing', 'talking'])
.limit(10)
.sort('-occupation')
.select('name occupation')
.exec(callback);

我很难理解.find({ occupation: /host/ }).select('name occupation')有什么不同。find是否添加了where这样的条件?还是控制返回的字段? 好吧,所以我看到选择只控制字段从查询的最终结果,但现在我不明白FindWhere是如何不同的。我不能使用FindWhere创建相同的查询吗?下面的代码片段相同吗?

Person
.where('occupation').equals('host')
.where('name.last').equals('Ghost')
.where('age').gt(17).lt(66)
.where('likes').in(['vaporizing', 'talking'])
.limit(10)
.sort('-occupation')
.select('name occupation')
.exec(callback);

来自select的API文档:

查询#select(arg)

指定要包含或排除哪些文档字段

.select('name occupation')说结果应该只包括nameoccupation字段。您不希望在结果中看到任何其他字段。

find描述了在结果中包含哪些文档。select指示这些文档的哪些字段应该在结果中可见。

find是实际的查询。在本例中,您将获得occupation等于host的所有行。现在,与该查询匹配的每个对象都有几个属性。让我们假设它具有nameageemailoccupation属性。当您指定您想要select nameoccupation时,您说您只想要这些属性。因此,在我们的例子中,ageemail将不会从查询中返回。

在这种情况下,

where用于指定要查询的多个约束。通常,使用where是因为它提供了比find更大的灵活性,例如传入javascript表达式

最新更新