Skip to content

Commit 5552107

Browse files
committedJun 4, 2023
fix(cursor): allow find middleware to modify query cursor options
Fix #13453 Backports #13435
1 parent 7a90868 commit 5552107

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed
 

‎lib/cursor/QueryCursor.js

+1
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ function QueryCursor(query, options) {
6666
// Max out the number of documents we'll populate in parallel at 5000.
6767
this.options._populateBatchSize = Math.min(this.options.batchSize, 5000);
6868
}
69+
Object.assign(this.options, query._optionsForExec());
6970
model.collection.find(query._conditions, this.options, (err, cursor) => {
7071
if (err != null) {
7172
_this._markError(err);

‎test/query.cursor.test.js

+24
Original file line numberDiff line numberDiff line change
@@ -844,6 +844,30 @@ describe('QueryCursor', function() {
844844
const docs = await Example.find().sort('foo');
845845
assert.deepStrictEqual(docs.map(d => d.foo), ['example1', 'example2']);
846846
});
847+
848+
it('should allow middleware to run before applying _optionsForExec() gh-13417', async function() {
849+
const testSchema = new Schema({
850+
a: Number,
851+
b: Number,
852+
c: Number
853+
});
854+
testSchema.pre('find', function() {
855+
this.select('-c');
856+
});
857+
const Test = db.model('gh13417', testSchema);
858+
await Test.create([{ a: 1, b: 1, c: 1 }, { a: 2, b: 2, c: 2 }]);
859+
const cursorMiddleSelect = [];
860+
let r;
861+
const cursor = Test.find().select('-b').sort({ a: 1 }).cursor();
862+
// eslint-disable-next-line no-cond-assign
863+
while (r = await cursor.next()) {
864+
cursorMiddleSelect.push(r);
865+
}
866+
assert.equal(typeof cursorMiddleSelect[0].b, 'undefined');
867+
assert.equal(typeof cursorMiddleSelect[1].b, 'undefined');
868+
assert.equal(typeof cursorMiddleSelect[0].c, 'undefined');
869+
assert.equal(typeof cursorMiddleSelect[1].c, 'undefined');
870+
});
847871
});
848872

849873
async function delay(ms) {

0 commit comments

Comments
 (0)
Please sign in to comment.