Mongoose Dates and Mixed objects not being saved to database

If you are working with Date or Mixed type objects in Mongoose you may notice that some objects are not always saved to the database, like they should, even if it looks like it just worked.

The Dates and Mixed types in Mongoose, are not attached to Mongoose' change tracking system, which means for any changes you make to those fields, they have to be marked as changed.

From the documentation on SchemaTypes:

Built-in Date methods are not hooked into the mongoose change tracking logic which in English means that if you use a Date in your document and modify it with a method like setMonth(), mongoose will be unaware of this change and doc.save() will not persist this modification.

Solution:

If we have a model field named _groups, of type mixed array, we would have to mark the field as modified before saving.

You can mark a field as modified like this:

document.markModified('fieldName');  

This way Mongoose will properly update the field in the database.

Contact.findById(id, function (err, contact) {  
  if (err && !contact) { return handleError(res, err); }

  contact._groups = ['some', 'new', 'ids']
  //Have to mark _groups array as modified:
  contact.markModified('_groups');

  contact.save(function (err, data) {
    if (err) { return handleError(res, err); }
    return res.json(200, contact);
  });
});
comments powered by Disqus