Document.prototype.getChanges()

Returns:
  • «Object»

Returns the changes that happened to the document in the format that will be sent to MongoDB.

Example:

  1. const userSchema = new Schema({
  2. name: String,
  3. age: Number,
  4. country: String
  5. });
  6. const User = mongoose.model('User', userSchema);
  7. const user = await User.create({
  8. name: 'Hafez',
  9. age: 25,
  10. country: 'Egypt'
  11. });
  12. // returns an empty object, no changes happened yet
  13. user.getChanges(); // { }
  14. user.country = undefined;
  15. user.age = 26;
  16. user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } }
  17. await user.save();
  18. user.getChanges(); // { }

Modifying the object that getChanges() returns does not affect the document’s change tracking state. Even if you delete user.getChanges().$set, Mongoose will still send a $set to the server.