查询(queries)

原文:Queriesarrow-up-right 翻译:小虾米(QQ:509129)

Queries

可以通过模型arrow-up-right的几个静态辅助方法检索文档。

任何涉及指定查询条件的模型arrow-up-right方法都可以执行两种方法:

当一个回调函数:

  • 通过,操作将立即执行,结果传递给回调。

  • 未通过,查询的一个实例被返回,它提供了一个特殊的查询生成器接口。

在mongoose 4,一个查询arrow-up-right有一个 .then()功能,因此可以被用来作为一个承诺。

当执行一个查询回调函数,你指定一个JSON文档作为你的查询。JSON文档的语法是MongoDB的shell一样。

var Person = mongoose.model('Person', yourSchema);

// find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
  if (err) return handleError(err);
  console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.
})

在这里,我们看到,查询立即执行,并将结果传递给我们的回调。所有在Mongoose的回调使用模式:callback(error, result)。如果执行查询时发生错误,则错误参数将包含一个错误文档,结果将是无效的。如果查询成功,错误参数将为空,结果将与查询的结果填充。

在Mongoose中任何一个回调传递给一个查询,回调如下模式callback(error, results)。什么样的结果是取决于操作:为 findone()arrow-up-right 它是一种单文档,find() arrow-up-right一个文档列表,count()arrow-up-right文档数量,update()arrow-up-right 文件数量等影响,API文档模型arrow-up-right提供更加详细的关于什么是传递给回调函数。

现在让我们看看在没有回调时发生了什么:

在上面的代码中,查询变量是类型查询arrow-up-right。查询允许您建立一个查询使用链式语法,而不是指定一个JSON对象。下面的2个例子是等价的。

一个完整的查询辅助功能列表可以在API文档arrow-up-right中找到。

其他文档的参考资料

There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where populationarrow-up-right comes in. Read more about how to include documents from other collections in your query results herearrow-up-right.

Streaming

你可以从MongoDB查询结果。你需要调用Query#cursor()arrow-up-right函数代替Query#execarrow-up-right返回一个 QueryCursorarrow-up-right实例。

下一步

既然我们已经掌握了查询,让我们看看验证arrow-up-right

Last updated