Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,13 @@ function applyGetters(schema, res) {
if (res == null) {
return;
}
// Skip applying getters if the `lean` option is false.
// This ensures that Mongoose getters are not applied to non-lean queries.
if (!this._mongooseOptions?.lean) {
return;
}
const { defaultLeanOptions } = this._mongooseLeanGettersOptions;
const shouldCallGetters = this._mongooseOptions?.lean?.getters ?? defaultLeanOptions?.getters ?? false;
const shouldCallGetters = this._mongooseOptions.lean.getters ?? defaultLeanOptions?.getters ?? false;

if (shouldCallGetters) {
if (Array.isArray(res)) {
Expand Down
7 changes: 6 additions & 1 deletion test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,8 @@ describe('mongoose-lean-getters', function() {
assert.equal(typeof found.discriminatedProp.num, 'string', 'Discriminated prop is not a string');
assert.equal(typeof found.discriminatedArray[0].num, 'string', 'Discriminated array is not a string');
});
it('allows defaultLeanOptions to be set and overridden at call time (#33)', async() => {

it('allows defaultLeanOptions to be set and overridden at call time (#33) (#46)', async() => {
const testSchema = new mongoose.Schema({
field: {
type: String,
Expand All @@ -458,6 +459,10 @@ describe('mongoose-lean-getters', function() {

const doc2 = await TestModel.findById(entry._id).lean({ getters: false });
assert.equal(doc2.field, 'value');

const doc3 = await TestModel.findById(entry._id);
assert.equal(doc3.field, 'value-suffix');
assert.equal(doc3.get('field', null, { getters: false }), 'value');
});

it('should allow non-discriminated documents to be retrieved (#39)', async() => {
Expand Down
Loading