Skip to content

Commit

Permalink
fix: handle getter for single nested that returns non-object #42
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Feb 24, 2025
1 parent f945539 commit 44dd2dd
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ function applyGettersToDoc(schema, doc) {
val[i] = schematype.caster.applyGetters(val[i], doc);
}
}
} if (val && schematype.$isSingleNested) {
} if (val && typeof val === 'object' && schematype.$isSingleNested) {
applyGettersToDoc.call(this, schematype.schema, val);
} else {
mpath.set(path, val, doc);
Expand Down
24 changes: 24 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -526,4 +526,28 @@ describe('mongoose-lean-getters', function() {
})
);
});

it('handles single nested getter that returns primitive (gh-42)', async function() {
const AccountSchema = new mongoose.Schema({
name: {
_id: false,
type: {
first: { type: String, required: true },
last: { type: String, required: true },
},
get: function(v) {
return v.first + v.last;
},
},
});
AccountSchema.plugin(mongooseLeanGetters);
const Account = mongoose.model('gh-42-subdoc-getter', AccountSchema);
const { _id } = await Account.create({
name: { first: 'Hamo', last: 'Boker' },
});
const account = await Account.findById(_id).lean({
getters: true,
});
assert.strictEqual(account.name, 'HamoBoker');
});
});

0 comments on commit 44dd2dd

Please sign in to comment.