I have a node.js app uses express and mongoose,
I have created my model as below
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;
and i am trying to add a new field here, so the schema objects looks like this
{
name: { type: String },
email: { type: String },
mynewfield: {type: String }
},
but when I create a new record as follows it doesn't write this new field into my database,
const newUser = new User({
name: 'John Doe',
email: '[email protected]',
mynewfield: 'some value'
});
new record looks like this
{
name: 'John Doe',
email: '[email protected]',
}
I have tried update updateMany but this is only updating the existing records it doesn't work when creating a new record.
What is the best way to add this new field into my schema so when i create a new entry it will be included?
CodePudding user response:
You have to set { strict: false }
to add new field in schema. Check the doc: strict
const thingSchema = new Schema({..}, { strict: false });
const thing = new Thing({ iAmNotInTheSchema: true });
thing.save(); // iAmNotInTheSchema is now saved to the db!!