如何在创建模型后更新 mongodb 架构

How to update mongodb schema after created the model

我有一个 node.js 应用程序使用 express 和 mongoose,

我创建的模型如下

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const userSchema = new Schema(
  {
    name: { type: String, required: true },
    email: { type: String, required: true },
  },
  {
    timestamps: true,
  }
)

const User = mongoose.model("User", userSchema);

module.exports = Lead;

我正在尝试在此处添加一个新字段,因此架构对象如下所示

{
    name: { type: String },
    email: { type: String },
    mynewfield: {type: String }
  },

但是当我如下创建新记录时,它不会将这个新字段写入我的数据库,

const newUser = new User({
    name: 'John Doe',
    email: 'john@email.com',
    mynewfield: 'some value'
});

新记录看起来像这样

{
    name: 'John Doe',
    email: 'john@email.com',
}

我已经尝试更新 updateMany 但这只是更新现有记录,它在创建新记录时不起作用。

将这个新字段添加到我的架构中的最佳方法是什么,以便在我创建新条目时将其包括在内?

您必须设置 { strict: false } 才能在架构中添加新字段。检查文档:strict

const thingSchema = new Schema({..}, { strict: false });
const thing = new Thing({ iAmNotInTheSchema: true });
thing.save(); // iAmNotInTheSchema is now saved to the db!!