如何使用 Mongoose 的 findOneAndUpdate 函数

发布于 2022-10-02 01:36:24 字数 3404 浏览 197 评论 0

Mongoose 的 findOneAndUpdate() 函数 找到与给定 匹配的第一个文档 filter,应用一个 update 并返回该文档。不同于 updateOne()findOneAndUpdate() 返回更新后的文档。
不像 save()findOneAndUpdate() 是原子的:文档在 MongoDB 找到文档和 MongoDB 应用更新之间不能更改。

开始入门

您至少需要 2 个参数才能调用 findOneAndUpdate():filterupdate,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 或中间件 updateOnesave 但它确实触发了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

辞别

暂无简介

文章
评论
545 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文