diff --git a/src/cursor/find_cursor.ts b/src/cursor/find_cursor.ts index 2bf9cffd2d..ae483ca215 100644 --- a/src/cursor/find_cursor.ts +++ b/src/cursor/find_cursor.ts @@ -412,11 +412,19 @@ export class FindCursor extends AbstractCursor { * @remarks * {@link https://docs.mongodb.com/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} */ - allowDiskUse(): this { + allowDiskUse(allow = true): this { assertUninitialized(this); + if (!this[kBuiltOptions].sort) { throw new MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification'); } + + // As of 6.0 the default is true. This allows users to get back to the old behaviour. + if (!allow) { + this[kBuiltOptions].allowDiskUse = false; + return this; + } + this[kBuiltOptions].allowDiskUse = true; return this; } diff --git a/test/integration/crud/find_cursor_methods.test.js b/test/integration/crud/find_cursor_methods.test.js index abaaf5bbaa..992e40d474 100644 --- a/test/integration/crud/find_cursor_methods.test.js +++ b/test/integration/crud/find_cursor_methods.test.js @@ -294,4 +294,58 @@ describe('Find Cursor', function () { }) }); }); + + context('#allowDiskUse', function () { + it('should set allowDiskUse to true by default', { + metadata: { requires: { mongodb: '>=4.4' } }, + test: withClientV2(function (client, done) { + const commands = []; + client.on('commandStarted', filterForCommands(['find'], commands)); + + const coll = client.db().collection('abstract_cursor'); + const cursor = coll.find({}, { sort: 'foo' }); + cursor.allowDiskUse(); + this.defer(() => cursor.close()); + + cursor.toArray(err => { + expect(err).to.not.exist; + expect(commands).to.have.length(1); + expect(commands[0].command.allowDiskUse).to.equal(true); + done(); + }); + }) + }); + + it('should set allowDiskUse to false if specified', { + metadata: { requires: { mongodb: '>=4.4' } }, + test: withClientV2(function (client, done) { + const commands = []; + client.on('commandStarted', filterForCommands(['find'], commands)); + + const coll = client.db().collection('abstract_cursor'); + const cursor = coll.find({}, { sort: 'foo' }); + cursor.allowDiskUse(false); + this.defer(() => cursor.close()); + + cursor.toArray(err => { + expect(err).to.not.exist; + expect(commands).to.have.length(1); + expect(commands[0].command.allowDiskUse).to.equal(false); + done(); + }); + }) + }); + + it('throws if the query does not have sort specified', { + metadata: { requires: { mongodb: '>=4.4' } }, + test: withClientV2(function (client, done) { + const coll = client.db().collection('abstract_cursor'); + const cursor = coll.find({}); + expect(() => cursor.allowDiskUse(false)).to.throw( + 'Option "allowDiskUse" requires a sort specification' + ); + done(); + }) + }); + }); });