Skip to content

BREAKING CHANGE: rely on transforms over middleware to apply virtuals and add findOneAndReplace support #76

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 14, 2025
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
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ jobs:
fail-fast: false
matrix:
node: [22]
os: [ubuntu-22.04]
os: [ubuntu-24.04]
name: TypeScript Test
steps:
- uses: actions/checkout@a12a3943b4bdde767164f792f33f40b04645d846 # v3
Expand Down
29 changes: 10 additions & 19 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,16 @@ const attachVirtualsFnMap = new WeakMap();

module.exports = function mongooseLeanVirtuals(schema, options) {
const fn = attachVirtualsMiddleware(schema, options);
schema.pre('find', function() {
if (typeof this.map === 'function') {
this.map((res) => {
fn.call(this, res);
return res;
});
} else {
this.options.transform = (res) => {
fn.call(this, res);
return res;
};
}
schema.pre(['find', 'findOne', 'findOneAndUpdate', 'findOneAndDelete', 'findOneAndReplace'], function mongooseLeanVirtualsMiddleware() {
const _this = this;
// Unshift ensures this transform runs before any other transforms and middleware (middleware runs after transforms).
// This is crucial to ensure that virtuals are applied to the data structure first, preventing user-specified transforms
// from operating on an unexpected or incomplete data structure. See gh-75 for more details.
this._transforms.unshift(function applyLeanVirtuals(res) {
fn.call(_this, res);
return res;
});
});

schema.post('find', fn);
schema.post('findOne', fn);
schema.post('findOneAndUpdate', fn);
schema.post('findOneAndRemove', fn);
schema.post('findOneAndDelete', fn);
};

module.exports.parent = function(obj) {
Expand All @@ -43,7 +34,7 @@ module.exports.parent = function(obj) {
};

function attachVirtualsMiddleware(schema, options = {}) {
return function(res) {
return function attachVirtualsToQueryResult(res) {
let virtuals = this._mongooseOptions.lean && this._mongooseOptions.lean.virtuals != null ? this._mongooseOptions.lean.virtuals : options.enabledByDefault;
if (virtuals) {
if (Array.isArray(virtuals)) {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"typescript": "5.x"
},
"peerDependencies": {
"mongoose": ">=5.11.10"
"mongoose": ">=8.0.0"
},
"author": "Valeri Karpov <val@karpov.io>",
"license": "Apache 2.0",
Expand Down
32 changes: 32 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ const supportedOps = {
leanOptions = leanOptions || defaultLeanOptions;
return model.findOneAndDelete({ _id: docId }).lean(leanOptions).exec();
},
'findOneAndReplace': function(model, docId, leanOptions) {
leanOptions = leanOptions || defaultLeanOptions;
return model.findOneAndReplace({ _id: docId }, { ...baseObj }).lean(leanOptions).exec();
}
};
const supportedOpsKeys = Object.keys(supportedOps);

Expand Down Expand Up @@ -808,6 +812,34 @@ describe('Discriminators work', () => {
);
});

it('with transform (gh-75)', async function() {
const schema = new mongoose.Schema({ name: String });
schema.virtual('lower').get(function() {
return this.name.toLowerCase();
});

schema.plugin(mongooseLeanVirtuals);
const Model = mongoose.model('gh75', schema);

await Model.create([
{ name: 'JOHN' },
{ name: 'JANE' }
]);

const docs = await Model.find().lean({ virtuals: true }).transform((docs) => {
const map = {};
docs.forEach(doc => {
map[doc._id.toString()] = doc;
});
return map;
});

assert.equal(Object.keys(docs).length, 2);
for (const [id, doc] of Object.entries(docs)) {
assert.equal(doc.name.toLowerCase(), doc.lower);
}
});

it('populates empty array instead of undefined for empty virtuals with justOne: false (Automattic/mongoose#10816)', async function() {
const matchSchema = new mongoose.Schema({
timestamp: { type: Number }
Expand Down
Loading