使用 Mongoose 插入文档

发布于 2022-07-29 00:28:22 字数 1883 浏览 183 评论 0

在 MongoDB 中,一个 upsert 意味着如果没有文档匹配则插入一个新文档的更新。 filter 要在 Mongoose 中插入文档,您应该设置 upsert 选项 Model.updateOne() 功能

const res = await Character.updateOne(
  { name: 'Jean-Luc Picard' },
  { $set: { age: 59 } },
  { upsert: true } // Make this update into an upsert
);

// Will be 1 if MongoDB modified an existing document, or 0
// if MongoDB inserted a new document.
res.nModified;
// Contains an array of descriptions of the documents inserted,
// including the `_id` of all inserted docs.
res.upserted;

要获取插入的文档,您应该使用 Model.findOneAndUpdate() 函数 代替 Model.updateOne()

 

const doc = await Character.findOneAndUpdate(
  { name: 'Jean-Luc Picard' },
  { $set: { age: 59 } },
  { upsert: true, new: true }
);

doc.name; // 'Jean-Luc Picard'
doc.age; // 59

Mongoose 最多会插入一个文档。 即使你使用 Model.updateMany() 和 upsert,Mongoose 最多会插入一个文档。 要批量更新多个文档,您应该 使用 Model.bulkWrite() 功能

const res = await Character.bulkWrite([
  {
    updateOne: {
      filter: { name: 'Will Riker' },
      update: { age: 29 },
      upsert: true
    }
  },
  {
    updateOne: {
      filter: { name: 'Geordi La Forge' },
      update: { age: 29 },
      upsert: true
    }
  }
]);

// Contains the number of documents that were inserted because
// of an upsert
res.upsertedCount;
// Contains the number of existing documents that were updated.
res.modifiedCount;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

关于作者

清眉祭

暂无简介

0 文章
0 评论
21 人气
更多

推荐作者

yangzhenyu123

文章 0 评论 0

lvzun

文章 0 评论 0

执笔绘流年

文章 0 评论 0

芯好空

文章 0 评论 0

始于初秋

文章 0 评论 0

谁与争疯

文章 0 评论 0

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