How to make mongoose fail if field is not in schema?

Viewed 896

I want mongoose fails if I try to save document with field which is not in schema.

I know about strict option (https://mongoosejs.com/docs/guide.html#strict), but it does not cover my needs. strict: true removes fields without warning. And strict: false allows to save everything (which is not good in long terms).

var thingSchema = new Schema({..}, { /* ?? */ })
var Thing = mongoose.model('Thing', thingSchema);
var thing = new Thing({ iAmNotInTheSchema: true });
thing.save();

Is there a way to provide some option so thing.save(); fails with error?

I'd like to turn this option on for local development. This way I can find typos and forgotten fields without hard debugging


Update to answer:

Following is true for mongoose v5.3.14. They may change it in future versions.

Keep in mind that "strict": "throw" does not cover all situations. Most of create/update operation will throw:

const model = new Model({ name: 'Mario', iAmNotInTheSchema: true })
await Model.create({ name: 'Mario', iAmNotInTheSchema: true })
await Model.updateOne({}, { iAmNotInTheSchema: true })
await Model.updateMany({}, { iAmNotInTheSchema: true })
await Model.findOneAndUpdate({}, { iAmNotInTheSchema: true })
await Model.findOneAndUpdate({}, { $set: { iAmNotInTheSchema: true } })

Error message is nice:

Field `iAmNotInTheSchema` is not in schema and strict mode is set to throw.

But for this case:

const model = await Model.findOne({})
model.iAmNotInTheSchema = true
await model.save()

it will not throw. The code runs without any errors, and iAmNotInTheSchema will be ignored (like with strict: true).

1 Answers

The strict option may also be set to "throw" which will cause errors to be produced instead of dropping the bad data.

There is an option passed to the schema constructor to throw errors on such conditions. Reference: https://mongoosejs.com/docs/guide.html#strict

new Schema({..}, {"strict": "throw"});
Related