Mongoose {strict: throw} doesn't throw error

If you add properties that are not part of the model, from mongoose doc :

The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db

It is working like this even with strict:throw, so you don't have to worry about additional fields not referenced in the model.

Concerning the exception not triggered, Aaron Heckmann talks about this in this post regarding that an exception that is not triggered on a save with strict : throw :

This is more a misunderstanding of how mongoose works. the 'strict' option enables validation of keys/values that are attempting to be stored in the db. schemas create getters/setters on document instances that delagate to the doc.{g,s}et() methods which are validated. attaching adhoc data to a mongoose document instance doesn't trigger get/set() and as such doesn't warrant validation since there's no way that day can get saved to the db.

As the additional fields are not part of the model, they don't trigger those validation so no exception is triggered (and of course those fields are not saved in the database)

Exceptions will be thrown only if your fields that belong to the model fail this validation


The docs say:

https://mongoosejs.com/docs/guide.html#strict

The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db

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

But it doesn't mean what you think it means.

NOTE: Any key/val set on the instance that does not exist in your schema is always ignored, regardless of schema option.

So 'Bad data' just encompasses data that is in the schema but wrong format. Any extra data NOT in the schema will just be silently deleted, causing maximum hair-loss and violating POLA.