Skip to content

Unexpected $unset fields in getChanges() when using defaultLeanOptions.getters and not using .lean() #46

@kubilay-guran-crea

Description

@kubilay-guran-crea

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:

  1. Set defaultLeanOptions.getters = true
  2. Perform a Mongoose .findOne() query without .lean() and with projecting some fields
  3. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions