From f232c41cb149f28956fd66a8cdc2bafaa9a24e7b Mon Sep 17 00:00:00 2001 From: Evan Nimmo Date: Wed, 24 Apr 2024 09:48:31 +1200 Subject: [PATCH] Add support for findOneAndReplace 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. --- index.js | 1 + test/index.test.js | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/index.js b/index.js index eaf2abb..82bef66 100644 --- a/index.js +++ b/index.js @@ -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) { diff --git a/test/index.test.js b/test/index.test.js index d163e46..2230bcb 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -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'); + }); });