[Mongoose] Check if Specific Fields Have Changed with isDirectModified, isModified, modifiedPaths

Tadashi Shigeoka ·  Fri, February 20, 2015

In Mongoose, you can check whether specific fields in a document have changed using methods like isDirectModified, isModified, and modifiedPaths.

mongoose | マングース

Mongoose provides functionality similar to Ruby on Rails ActiveRecord’s changed? and attribute_name_changed? methods.

Let me introduce them one by one.

Document#isDirectModified(path)

The isDirectModified method returns true if the field specified in the argument itself has been changed, and false otherwise.

doc.set('documents.0.title', 'changed');

// Returns true because 'documents.0.title' itself has been changed
doc.isDirectModified('documents.0.title') // true

// Returns false because 'documents' itself hasn't changed, even though there are changes in lower hierarchy
doc.isDirectModified('documents') // false

Document#isModified([path])

The isModified method returns true if any area related to the field specified in the argument has been changed, and false otherwise.

doc.set('documents.0.title', 'changed');

// Returns true for the changed field and its containing upper hierarchy
doc.isModified()                    // true
doc.isModified('documents')         // true
doc.isModified('documents.0.title') // true

// Returns false when specifying an unchanged field
doc.isModified('something')         // false

// Returns false because 'documents' itself hasn't changed, even though there are changes in lower hierarchy
doc.isDirectModified('documents')   // false

Document#modifiedPaths()

The modifiedPaths method returns an Array of field names that have been changed.

doc.set('name', 'test name');
doc.set('documents.0.title', 'changed');

doc.modifiedPaths()
[ 'name',
  'documents.0.title' ]

It would be great to use these features skillfully to write clean logic.

That’s all from the Gemba.