Skip to content
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

fix query cursor and middleware interaction #13435

Merged
merged 2 commits into from
May 24, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/cursor/QueryCursor.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ function QueryCursor(query, options) {
this._transforms = [];
this.model = model;
this.options = options || {};

model.hooks.execPre('find', query, (err) => {
if (err != null) {
_this._markError(err);
Expand All @@ -66,6 +65,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);
Expand Down
1 change: 1 addition & 0 deletions lib/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -5021,6 +5021,7 @@ Query.prototype.cursor = function cursor(opts) {
}

const options = this._optionsForExec();

try {
this.cast(this.model);
} catch (err) {
Expand Down
23 changes: 23 additions & 0 deletions test/query.cursor.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,29 @@ 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) {
Expand Down