我有一個使用 express 和 mongoose 的 node.js 應用程式,
我已經創建了我的模型如下
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: '[email protected]',
mynewfield: 'some value'
});
新記錄看起來像這樣
{
name: 'John Doe',
email: '[email protected]',
}
我已經嘗試過 update updateMany 但這只是更新現有記錄,在創建新記錄時它不起作用。
將此新欄位添加到我的架構中的最佳方法是什么,以便在我創建新條目時將其包含在內?
uj5u.com熱心網友回復:
您必須設定{ strict: false }在架構中添加新欄位。檢查檔案: 嚴格
const thingSchema = new Schema({..}, { strict: false });
const thing = new Thing({ iAmNotInTheSchema: true });
thing.save(); // iAmNotInTheSchema is now saved to the db!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/429513.html
上一篇:查詢mongodb的嵌套物件
