Skip to content

Commit

Permalink
BREAKING CHANGE: call getters correctly on array elements for Mongoos…
Browse files Browse the repository at this point in the history
…e 7.5.0, require Mongoose 7.5.0

Fix #30
  • Loading branch information
vkarpov15 committed Mar 7, 2024
1 parent bbd2159 commit eddaebb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
16 changes: 14 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,20 @@ function applyGettersToDoc(schema, doc, fields, prefix) {
!this.isPathSelectedInclusive(pathWithPrefix)) {
return;
}
if (mpath.has(path, doc)) {
mpath.set(path, schematype.applyGetters(mpath.get(path, doc), doc, true), doc);

const pathExists = mpath.has(path, doc);
if (pathExists) {
if (schematype.$isMongooseArray && !schematype.$isMongooseDocumentArray) {
mpath.set(
path,
schematype.applyGetters(mpath.get(path, doc), doc, true).map(subdoc => {
return schematype.caster.applyGetters(subdoc, doc);
}),
doc
);
} else {
mpath.set(path, schematype.applyGetters(mpath.get(path, doc), doc, true), doc);
}
}
});
}
Expand Down
26 changes: 26 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,4 +249,30 @@ describe('mongoose-lean-getters', function() {

assert.equal(docs[0].url, 'https://www.test.com discriminator field');
});

it('should call getters on arrays (gh-30)', async function() {
function upper(value) {
return value.toUpperCase();
}

const userSchema = new mongoose.Schema({
name: {
type: String,
get: upper
},
emails: [{ type: String, get: upper }]
});
userSchema.plugin(mongooseLeanGetters);
const User = mongoose.model('User', userSchema);

const user = new User({
name: 'one',
emails: ['two', 'three'],
});
await user.save();

const foundUser = await User.findById(user._id).lean({ getters: true });
assert.strictEqual(user.name, 'ONE');
assert.deepStrictEqual(foundUser.emails, ['TWO', 'THREE']);
});
});

0 comments on commit eddaebb

Please sign in to comment.