mongoose 文档(四) queries

Queries

通过一些model的静态辅助方法可以检索document。

任何 涉及 指定 查询 条件的 model 方法都能通过两个方法执行。

当一个回调函数:

  1. 被传递,操作将立即执行,结果传给回调。
  2. 没有被传递,返回一个 查询 实例,它提供一个特殊的查询生成接口。

在mongoose 4,Query有 then()函数,因此可以被用来作为一个 promise。

用回调函数执行查询时,将查询指定为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)。如果执行查询中发生错误,error参数会包含一个错误文档,result会是null。如果查询成功,error参数会是null,result会是请求结果。

在mongoose任何地方 回调被传递给查询,回调遵循模式 callback(error, results)。结果取决于运算符:findOne() 是一个可能为空的单document,find()为一列document,count()为document的数目,update() 为受影响的document数量Model的API文档详细介绍什么传递给了回调。

 现在看看在没有回调的情况下会发生什么:

// find each person with a last name matching 'Ghost'
var query = Person.findOne({ 'name.last': 'Ghost' });

// selecting the `name` and `occupation` fields
query.select('name occupation');

// execute the query at a later time
query.exec(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.
})

 在上面的代码,query变量是Query类型。Query允许你使用链接语法建立查询而不是指定JSON对象。下面两个例子 是等价的。

// With a JSON doc
Person.
  find({
    occupation: /host/,
    'name.last': 'Ghost',
    age: { $gt: 17, $lt: 66 },
    likes: { $in: ['vaporizing', 'talking'] }
  }).
  limit(10).
  sort({ occupation: -1 }).
  select({ name: 1, occupation: 1 }).
  exec(callback);
  
// Using query builder
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);

API文档中有查询辅助函数列表。

1、引用其他document

MongoDB中没有joins但有时候我们仍想引用其他collection的document。这就是population的由来。查看如何在查询结果中包含其他collection的document。

2、stream

查询也能以从MongoDB到应用程序。仅仅调用查询的stream方法代替exec返回一个QuerySteam的实例。QueryStreams是Node.js 0.8风格的输入流不是Node.js 0.10 风格。

原文地址:https://www.cnblogs.com/surahe/p/5184479.html