-
Notifications
You must be signed in to change notification settings - Fork 15
Description
Description:
When working with normal Mongoose documents (i.e., not using .lean()), we noticed unexpected $unset operations in the result of doc.getChanges(), even though we made no changes to the document.
This happens when defaultLeanOptions.getters is set to true, and the fields in question are not projected in the query. In this scenario, although .lean() was not used, the non-projected fields get marked for $unset in the internal tracking, which is not expected behavior.
Example scenario:
- Set defaultLeanOptions.getters = true
- Perform a Mongoose .findOne() query without .lean() and with projecting some fields
- Immediately call doc.getChanges() on the resulting document
We expect the result to show no changes, but instead we get $unset operations for the non-projected fields.
Root cause:
The issue seems to stem from this line in mongoose-lean-getters:
const shouldCallGetters = this._mongooseOptions?.lean?.getters ?? defaultLeanOptions?.getters ?? false;In this check, if defaultOptions.getter is true, getters will be applied even when .lean() was not used
Suggestion:
const shouldCallGetters = this._mongooseOptions?.lean && (this._mongooseOptions?.lean?.getters ?? defaultLeanOptions?.getters ?? false);This would prevent mongoose-lean-getters from applying to non-lean queries where it should have no effect.