Mongoose 中的查询简介
许多 Mongoose 模型函数,例如 find()
,返回一个 Mongoose 查询 。 的 Mongoose Query 类 提供了一个 链接接口 用于查找、更新和删除文档
const Character = mongoose.model('Character', Schema({
name: String,
age: Number
}));
const query = Character.find();
query instanceof mongoose.Query; // true
// Execute the query
const docs = await query;
链接
第一个参数 Model.find()
称为查询 过滤器 。 你调用 find()
MongoDB 将返回所有匹配查询过滤器的文档。
您可以使用 Mongoose 的 众多查询助手 来构建查询过滤器。 只需确保您指定要添加到过滤器的属性名称 where()
。
let docs = await Character.find().
// `where()` specifies the name of the property
where('name').
// and then the query helper `in()` specifies that `name`
// must be one of the 2 values in the array
in(['Jean-Luc Picard', 'Will Riker']);
// Equivalent query, but with the filter expressed as an object rather
// than using chaining
docs = await Character.find({
name: { $in: ['Jean-Luc Picard', 'Will Riker'] }
});
可链接操作允许您添加到当前查询过滤器。 您可以使用 Query#getFilter()
功能 。
const query = Character.find().
where('name').in(['Jean-Luc Picard', 'Will Riker']);
// `{ name: { $in: ['Jean-Luc Picard', 'Will Riker'] } }`
query.getFilter();
以下是几个有用的查询助手的列表:
lt(value)
,gt(value)
: 指定一个属性必须小于(lt()
)或大于 (gt()
) 一个值。value
可以是数字、字符串或日期。lte(value)
,gte(value)
: 指定一个属性必须大于或等于 (gte()
),或小于或等于 (gte()
), 一个值。in(arr)
: 指定一个属性必须等于指定的值之一arr
nin(arr)
: 指定一个属性 不能 等于任何指定的值arr
eq(val)
: 指定一个属性必须等于val
ne(val)
: 指定一个属性 不能 等于val
regex(re)
: 指定一个属性必须是一个匹配的字符串re
你可以链接任意多个 where()
调用和查询助手来构建您的查询。 例如:
const docs = await Character.find().
// `name` must match the regular expression
where('name').regex(/picard/i).
// `age` must be between 29 and 59
where('age').gte(29).lte(59);
执行
Mongoose 查询 不是 Promise 。 关键的区别在于,Mongoose 在您明确执行查询之前实际上不会将您的查询发送到服务器。 有两种方法可以执行查询:
Query#exec()
: 执行查询并返回 原生 JavaScript 承诺 。
const promise = Character.find().exec();
promise instanceof Promise; // true
promise instanceof mongoose.Query; // false
const docs = await promise;
Query#then()
和Query#catch()
:为查询提供了一个伪 Promise API,所以你可以await
在 Mongoose 查询中。 您还可以将 Promise 链与 Mongoose 查询一起使用,如下所示。
return Character.find().then(docs => {
docs; // List of docs
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论