Skip to content

Commit

Permalink
fix(cast): cast $comment to string in query filters
Browse files Browse the repository at this point in the history
Fix #14576
  • Loading branch information
vkarpov15 committed May 13, 2024
1 parent 07cb7da commit a70ecc2
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
4 changes: 4 additions & 0 deletions lib/cast.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const CastError = require('./error/cast');
const StrictModeError = require('./error/strict');
const Types = require('./schema/index');
const cast$expr = require('./helpers/query/cast$expr');
const castString = require('./cast/string');
const castTextSearch = require('./schema/operators/text');
const get = require('./helpers/get');
const getConstructorName = require('./helpers/getConstructorName');
Expand Down Expand Up @@ -89,6 +90,9 @@ module.exports = function cast(schema, obj, options, context) {
val = cast(schema, val, options, context);
} else if (path === '$text') {
val = castTextSearch(val, path);
} else if (path === '$comment' && !schema.paths.hasOwnProperty('$comment')) {
val = castString(val, path);
obj[path] = val;
} else {
if (!schema) {
// no casting for Mixed types
Expand Down
2 changes: 1 addition & 1 deletion lib/schema/operators/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const castString = require('../../cast/string');
* @api private
*/

module.exports = function(val, path) {
module.exports = function castTextSearch(val, path) {
if (val == null || typeof val !== 'object') {
throw new CastError('$text', val, path);
}
Expand Down
27 changes: 27 additions & 0 deletions test/cast.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,33 @@ describe('cast: ', function() {
});
});

it('casts $comment (gh-14576)', function() {
const schema = new Schema({ name: String });

let res = cast(schema, {
$comment: 'test'
});
assert.deepStrictEqual(res, { $comment: 'test' });

res = cast(schema, {
$comment: 42
});
assert.deepStrictEqual(res, { $comment: '42' });

assert.throws(
() => cast(schema, {
$comment: { name: 'taco' }
}),
/\$comment/
);

const schema2 = new Schema({ $comment: Number });
res = cast(schema2, {
$comment: 42
});
assert.deepStrictEqual(res, { $comment: 42 });
});

it('avoids setting stripped out nested schema values to undefined (gh-11291)', function() {
const nested = new Schema({}, {
id: false,
Expand Down

0 comments on commit a70ecc2

Please sign in to comment.