Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Mongoose defaults get applied to existing documents?

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?

like image 334
Tamlyn Avatar asked Jan 28 '16 16:01

Tamlyn


2 Answers

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 leanThing.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).

like image 111
Tamlyn Avatar answered Oct 19 '22 13:10

Tamlyn


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.

like image 28
Andrew Homeyer Avatar answered Oct 19 '22 13:10

Andrew Homeyer