If I add a property to a Mongoose schema and give it a default value, will existing documents receive these defaults when they are loaded?
Yes, but not if the query is lean
.
For queries that return a full Mongoose document object – Thing.find({...})
– the default value will be returned whenever the property is missing, regardless of when the schema was changed. If the document is subsequently saved, the default value will be materialised in the database.
If the query is lean
– Thing.find({...}).lean()
– the query returns only what's in the database and this doesn't include any newly added defaults (unless the document has been loaded and saved, as above).
You can customize default
to ignore the case where documents already exist.
Instead of doing default: Date.now
, where existing documents when fetched will show the current date even if it's not set in the db, you could do this:
default: function() {
if (this.isNew) {
return Date.now();
}
return void 0;
}
Now, existing documents that do not have the field set in the db will not have it set when fetched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With