Model 的多个静态辅助方法都可以查询文档,方法中包含查询条件参数的(find, findById, count, update)都按以下两种方法执行:
- 传入
callback
参数,操作会立即执行,查询结果被传给回调函数 - 不传
callback
参数,返回Query的一个实例,这个query提供了构建查询器的特殊接口
如果执行查询时传入 callback
参数,就需要用 JSON 文档的格式指定查询条件。
var Person = mongoose.model('Person', yourSchema);
// 查询每个 last name 是 'Ghost' 的 person, select `name` 和 `occupation` 字段
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
if (err) return handleError(err);
// Prints "Space Ghost is a talk show host".
// 用了这么多年才知道console还有%s %d占位符
console.log('%s %s is a %s.', person.name.first, person.name.last,
person.occupation);
});
上例中查询被立即执行,查询结果被传给回调函数。Mongoose 中所有的回调函数都使用 callback(error, result)
这种模式。如果查询时发生错误,error
参数即是错误文档, result
参数会是 null
。如果查询成功,error
参数是 null
,result
即是查询的结果。
Mongoose 中每一处查询,被传入的回调函数都遵循 callback(error, result)
这种模式。查询结果的格式取决于做什么操作: findOne()
是单个文档(有可能是 null ),find()
是文档列表, count()
是文档数量,update()
是被修改的文档数量。
下面来看不传入 callback
这个参数会怎样:
// 查询每个 last name 是 'Ghost' 的 person
var query = Person.findOne({ 'name.last': 'Ghost' });
// select `name` 和 `occupation` 字段
query.select('name occupation');
// 然后执行查询
query.exec(function (err, person) {
if (err) return handleError(err);
// Prints "Space Ghost is a talk show host."
console.log('%s %s is a %s.', person.name.first, person.name.last,
person.occupation);
});
以上代码中,query
是个 Query 类型的变量。 Query
能够用链式语法构建查询器,无需指定 JSON 对象。 下面2个示例等效。
// 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);
以下列举出个人认为可能常用的方法
- where() 类似model里的查询条件(conditions)
- equals() where指定一个字段后,做等值比较。
- or() 类似$or
- nor() 类似$nor
- and() 类似$and
- gt(), gte(), lt(), lte(), ne(), in(), nin(), all(),size(), regex() 查询条件
- slice() 对数组做切片映射,两个参数slice([path],val),实例:
query.slice('comments', [10, 5])
- limit() 指定查询结果的最大条数,一个参数 limit(val),不能和
distinct()
一起使用 - skip() 指定跳过的文档数,一个参数 skip(val),不能和
distinct()
一起使用 - select() 类似投影,一个参数 select(arg)
- getQuery() 以 JSON 对象格式返回当前的query conditions
- count() 传入两个可选参数count([conditions, callback]),传入callback 时会启动查询,会触发
count()
中间件 - sort() 设置排序,如果传入的参数是个对象,字段值可以是
asc
,desc
,ascending
,descending
,1
和-1
。 - exec() 执行查询,一般用于独立的动作一次性执行
存入与更新操作时,为了验证带插入的文档正确性,可以使用验证机制
)
同时支持中间件机制,分为document中间件, model中间件, aggregate中间件, query中间件,对原子化模型逻辑很有帮助,具体参考中间件。
MongoDB 3.2 之后,也有像 sql 里 join 的聚合操作,那就是 $lookup 而 Mongoose,拥有更强大的 populate()
,可以让你在别的 collection 中引用 document。具体参考填充。
网友评论