如何使用 Mongoose 的 findOneAndUpdate 函数
Mongoose 的 findOneAndUpdate()
函数 找到与给定 匹配的第一个文档 filter
,应用一个 update
并返回该文档。不同于 updateOne()
,findOneAndUpdate()
返回更新后的文档。
不像 save()
、findOneAndUpdate()
是原子的:文档在 MongoDB 找到文档和 MongoDB 应用更新之间不能更改。
开始入门
您至少需要 2 个参数才能调用 findOneAndUpdate()
:filter
和 update
,MongoDB 找到第一个匹配 filter
并应用的文档 update
。默认情况下,findOneAndUpdate()
返回 MongoDB 应用之前 update
的文档。
const Character = mongoose.model('Character', Schema({
name: String,
rank: String
}));
await Character.create({ name: 'Luke Skywalker' });
// By default, `findOneAndUpdate()` returns the document as
// it was **before** MongoDB applied the update.
const filter = { name: 'Luke Skywalker' };
const update = { rank: 'Jedi Knight' };
let doc = await Character.findOneAndUpdate(filter, update);
doc.name; // 'Luke Skywalker'
doc.rank; // undefined
// But the document is updated in the database:
doc = await Character.findOne(filter);
doc.rank; // 'Jedi Knight'
要在 MongoDB 应用给定后返回文档 update
,您需要将 new
选项设置为 true
:
// If you set the `new` option to `true`, Mongoose will
// return the document with the update applied.
const filter = { name: 'Luke Skywalker' };
const update = { rank: 'Jedi Knight' };
const opts = { new: true };
let doc = await Character.findOneAndUpdate(filter, update, opts);
doc.name; // 'Luke Skywalker'
doc.rank; // 'Jedi Knight'
Upserts
有几个其他选项 findOneAndUpdate()
。例如如果没有匹配的文档,您可以设置插入新文档的 upsert
选项filter
。
await Character.deleteMany({});
const filter = { name: 'Luke Skywalker' };
const update = { rank: 'Jedi Knight' };
// If you set the `upsert` option, Mongoose will insert
// a new document if one isn't found.
const opts = { new: true, upsert: true };
let doc = await Character.findOneAndUpdate(filter, update, opts);
doc.name; // 'Luke Skywalker'
doc.rank; // 'Jedi Knight'
// If `new` is `false` and an upsert happened,
// `findOneAndUpdate()` will return `null`
await Character.deleteMany({});
opts.new = false;
doc = await Character.findOneAndUpdate(filter, update, opts);
doc; // null
中间件
Mongoose 有专门的中间件用于 findOneAndUpdate()
,调用 findOneAndUpdate()
不会触发、findOne
或中间件 updateOne
。save
但它确实触发了 findOneAndUpdate
中间件。
const schema = Schema({
name: String,
rank: String
});
schema.pre('findOneAndUpdate', function middleware() {
this.getFilter(); // { name: 'Luke Skywalker' }
this.getUpdate(); // { rank: 'Jedi Knight' }
});
const Character = mongoose.model('Character', schema);
const filter = { name: 'Luke Skywalker' };
const update = { rank: 'Jedi Knight' };
// Mongoose calls the `middleware()` function above
await Character.findOneAndUpdate(filter, update, opts);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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