Cannot add property to mongoose document

I have a mongoose model with a few properties and strict option set to false. I create an empty document from this model and I want to add properties to it. The ones defined in the schema will be added to the object and the undefined ones won’t.

let mySchema = new mongoose.Schema({definedInSchema: {type: boolean}}, {strict: false});
const myModel = mongoose.model('name', mySchema);
let properties = {
   definedInSchema: true,
   undefinedInSchema: true
let myDocument = new myModel();
for (let i in properties)
   myDocument[i] = properties[i];
//output: the object myDocument doesn't have the property that wasn't defined in the schema.

What’s wrong here?


A model instance is more than just a simple javascript object, there is an internal _doc that is used to keep track of the value of each field. Getter and setter functions are automatially created for the fields defined in the schema, and fields added when the model in instantiated like

const thing = new Thing({ iAmNotInTheSchema: true });

Note that this is the way the documentation shows to have fields not in the schema.

If you create the document like this, undefinedInSchema will be accessible in the normal way:

let myDocument = new myModel(properties);

If you really do need additional fields after the object is created, you will need to explicitly call set, like

for (let i in properties)
    myDocument.set(i, properties[i]);