Skip to content

Commit

Permalink
fix(query): allow calling limit() and skip() with a string
Browse files Browse the repository at this point in the history
Fix #11017
  • Loading branch information
vkarpov15 committed Jan 4, 2022
1 parent 0c1fdbc commit d5550a5
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
46 changes: 46 additions & 0 deletions lib/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const applyGlobalMaxTimeMS = require('./helpers/query/applyGlobalMaxTimeMS');
const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
const cast = require('./cast');
const castArrayFilters = require('./helpers/update/castArrayFilters');
const castNumber = require('./cast/number');
const castUpdate = require('./helpers/query/castUpdate');
const completeMany = require('./helpers/query/completeMany');
const get = require('./helpers/get');
Expand Down Expand Up @@ -804,6 +805,21 @@ Query.prototype.mod = function() {
* @api public
*/

Query.prototype.limit = function limit(v) {
this._validate('limit');

if (typeof v === 'string') {
try {
v = castNumber(v);
} catch (err) {
throw new CastError('Number', v, 'limit');
}
}

this.options.limit = v;
return this;
};

/**
* Specifies the number of documents to skip.
*
Expand All @@ -823,6 +839,21 @@ Query.prototype.mod = function() {
* @api public
*/

Query.prototype.skip = function skip(v) {
this._validate('skip');

if (typeof v === 'string') {
try {
v = castNumber(v);
} catch (err) {
throw new CastError('Number', v, 'skip');
}
}

this.options.skip = v;
return this;
};

/**
* Specifies the maxScan option.
*
Expand Down Expand Up @@ -1583,6 +1614,21 @@ Query.prototype.setOptions = function(options, overwrite) {
// deleting options.defaults will cause 7287 to fail
}

if (typeof options.limit === 'string') {
try {
options.limit = castNumber(options.limit);
} catch (err) {
throw new CastError('Number', options.limit, 'limit');
}
}
if (typeof options.skip === 'string') {
try {
options.skip = castNumber(options.skip);
} catch (err) {
throw new CastError('Number', options.skip, 'skip');
}
}

return Query.base.setOptions.call(this, options);
};

Expand Down
10 changes: 9 additions & 1 deletion test/query.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -763,9 +763,17 @@ describe('Query', function() {
it('works', function(done) {
const query = new Query({});
query.limit(5);
assert.equal(query.options.limit, 5);
assert.strictEqual(query.options.limit, 5);
done();
});

it('with string limit (gh-11017)', function() {
const query = new Query({});
query.limit('5');
assert.strictEqual(query.options.limit, 5);

assert.throws(() => query.limit('fail'), /CastError/);
});
});

describe('skip', function() {
Expand Down

0 comments on commit d5550a5

Please sign in to comment.