在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这样的条件?还是控制返回的字段? 好吧,所以我看到选择只控制字段从查询的最终结果,但现在我不明白Find
和Where
是如何不同的。我不能使用Find
和Where
创建相同的查询吗?下面的代码片段相同吗?
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')
说结果应该只包括name
和occupation
字段。您不希望在结果中看到任何其他字段。
find
描述了在结果中包含哪些文档。select
指示这些文档的哪些字段应该在结果中可见。
find
是实际的查询。在本例中,您将获得occupation
等于host
的所有行。现在,与该查询匹配的每个对象都有几个属性。让我们假设它具有name
、age
、email
和occupation
属性。当您指定您想要select
name
和occupation
时,您说您只想要这些属性。因此,在我们的例子中,age
和email
将不会从查询中返回。
where
用于指定要查询的多个约束。通常,使用where
是因为它提供了比find
更大的灵活性,例如传入javascript表达式