Skip to content

Commit

Permalink
Add support for findOneAndReplace
Browse files Browse the repository at this point in the history
findOneAndReplace is currently not supported. This is required since
a change in mongoose (commit 0caeb6b2e8428cb56573b75212ddb7c186c2725d)
swapped findOneAndUpdate with the overwrite option set to use
findOneAndReplace which is not supported by mongoose-lean-getters.
  • Loading branch information
Evann-atl committed Apr 23, 2024
1 parent 87eb2ca commit f232c41
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ module.exports = function mongooseLeanGetters(schema) {
schema.post('findOne', fn);
schema.post('findOneAndUpdate', fn);
schema.post('findOneAndDelete', fn);
schema.post('findOneAndReplace', fn);
};

function applyGettersMiddleware(schema) {
Expand Down
21 changes: 21 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -330,4 +330,25 @@ describe('mongoose-lean-getters', function() {
assert.strictEqual(user.name, 'ONE');
assert.deepStrictEqual(foundUser.emails, ['TWO', 'THREE']);
});

it('should work with findOneAndReplace (gh-31)', async function() {
const testSchema = new mongoose.Schema({
field: Number,
otherField: Number
});
testSchema.plugin(mongooseLeanGetters);

testSchema.path('field').get(function(field) {
return field.toString();
});
const Test = mongoose.model('gh-31', testSchema);

await Test.deleteMany({});
const entry = await Test.create({
field: 1337
});
const doc = await Test.findOneAndReplace({ _id: entry._id }, entry).lean({ getters: true });
assert.equal(typeof doc.field, 'string');
assert.equal(doc.field, '1337');
});
});

0 comments on commit f232c41

Please sign in to comment.