From 55521079afb9e40afb959d84f072f85e3f9d2b3a Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Sat, 3 Jun 2023 20:45:07 -0400 Subject: [PATCH] fix(cursor): allow find middleware to modify query cursor options Fix #13453 Backports #13435 --- lib/cursor/QueryCursor.js | 1 + test/query.cursor.test.js | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/cursor/QueryCursor.js b/lib/cursor/QueryCursor.js index 06d083697c9..96fbc80dd67 100644 --- a/lib/cursor/QueryCursor.js +++ b/lib/cursor/QueryCursor.js @@ -66,6 +66,7 @@ function QueryCursor(query, options) { // Max out the number of documents we'll populate in parallel at 5000. this.options._populateBatchSize = Math.min(this.options.batchSize, 5000); } + Object.assign(this.options, query._optionsForExec()); model.collection.find(query._conditions, this.options, (err, cursor) => { if (err != null) { _this._markError(err); diff --git a/test/query.cursor.test.js b/test/query.cursor.test.js index 6f22c0eab4d..a4c8ea92dd0 100644 --- a/test/query.cursor.test.js +++ b/test/query.cursor.test.js @@ -844,6 +844,30 @@ describe('QueryCursor', function() { const docs = await Example.find().sort('foo'); assert.deepStrictEqual(docs.map(d => d.foo), ['example1', 'example2']); }); + + it('should allow middleware to run before applying _optionsForExec() gh-13417', async function() { + const testSchema = new Schema({ + a: Number, + b: Number, + c: Number + }); + testSchema.pre('find', function() { + this.select('-c'); + }); + const Test = db.model('gh13417', testSchema); + await Test.create([{ a: 1, b: 1, c: 1 }, { a: 2, b: 2, c: 2 }]); + const cursorMiddleSelect = []; + let r; + const cursor = Test.find().select('-b').sort({ a: 1 }).cursor(); + // eslint-disable-next-line no-cond-assign + while (r = await cursor.next()) { + cursorMiddleSelect.push(r); + } + assert.equal(typeof cursorMiddleSelect[0].b, 'undefined'); + assert.equal(typeof cursorMiddleSelect[1].b, 'undefined'); + assert.equal(typeof cursorMiddleSelect[0].c, 'undefined'); + assert.equal(typeof cursorMiddleSelect[1].c, 'undefined'); + }); }); async function delay(ms) {