【问题标题】:How to add a new field to an existing MongoDB document using Mongoose?如何使用 Mongoose 向现有 MongoDB 文档添加新字段?
【发布时间】:2023-02-14 17:19:46
【问题描述】:

我已经尝试了很多次向现有的 MongoDB 文档添加新字段,但都失败了。我尝试按照代码来完成这项工作,但什么也没发生。

这里是用户模型。

const UserSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

这是向文档添​​加新字段的代码。

const updateDocument = async () => {
  const updatedUser = await User.findOneAndUpdate(
    { _id: "63eb30f466127f7a0f7a9b32" },
    {
      $set: { lastName: "syed" },
    }
  );
  console.log(updatedUser);
};

updateDocument();

注 1: lastName 字段在 MongoDB 文档和 UserSchema 中不存在。我想将该字段添加到 MongoDB 文档中。

笔记2:当我更新文档中的现有字段时,相同的代码有效,但在添加新字段时不起作用。

【问题讨论】:

    标签: node.js mongodb mongoose next.js


    【解决方案1】:

    您需要将strict:false 作为findOneAndUpdate 的选项传递。

    根据猫鼬doc

    strict 选项(默认启用)确保传递给模型构造函数但未在我们的模式中指定的值不会保存到数据库中。

    const updatedUser = await User.findOneAndUpdate(
      { _id: "63eb30f466127f7a0f7a9b32" },
      {
        $set: { lastName: "syed" },
      },
      { strict: false }
    );
    

    【讨论】:

      猜你喜欢
      • 2014-07-20
      • 2017-06-26
      • 2012-10-27
      • 2012-04-22
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多