Automattic / Automattic/mongoose

Proposal: wasModified() check

Open
#7,245 2 comments 2 reactions 0 assignees View on GitHub
discussion
Dominant language
JavaScript
Stars
27.5k
Forks
4k
Avg merge
2d 7h
Merged PRs (30d)
35

Description

**Do you want to request a *feature* or report a *bug*?**
Feature

**What is the current behavior?**
There is no ability to detect if a property _was_ modified after a `save` operation, except by manual tracking of properties, the thought of which makes you 🤢.

**Use case**
I need to update denormalized data across several collections, _AFTER_ my document is saved. I don't want to denormalize _BEFORE_ the document gets saved.

So I want to make a post save hook on the model like so:

```js
/**
* Update denormalized data
*/
ProjectSchema.post('save', async function(next) {

//Check if name modified
if (!this.isModified('name')) {
return next();
}

//Make patch
const {_id, name} = this;
const patch = {name};
const models = ['Contract'];

//Update models
await Promise
.map(models, model => mongoose
.model(model)
.updateDenormalized('project', _id, patch));

//Onwards
next();
});
```

The problem is, that since this code runs _after_ the save, the `isModified` flag will come back as false, always. So there is no way to detect in a post-save hook if a property was modified in the preceding save operation, unless I use _another_ pre-save hook and a bunch of helper properties to track modified state.

A `wasModified` check could solve this by checking and storing which properties have been modified just before a save operation, and making this available for querying through a `wasModified(key)` method.

If the document fails to save, the method will return false.

Thoughts? I can look at submitting a PR if you think this would make sense.

Contributor guide

Open the contributing guide

Research direction

Start by tracing Mongoose document save middleware, especially the post('save') and pre-save hook behavior described in the issue, along with the existing isModified check. Define how modified paths should be captured before saving, exposed through wasModified(key), and reset when a save fails. Done means a post-save hook can reliably detect changes from the preceding save without manual tracking.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, mongodb, nodejs
Domain
backend, database
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.