Skip to content

Commit eb61572

Browse files
authoredMay 15, 2024··
Merge pull request #14590 from Automattic/vkarpov15/gh-14576
fix(cast): cast $comment to string in query filters
2 parents 07cb7da + a70ecc2 commit eb61572

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed
 

‎lib/cast.js

+4
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const CastError = require('./error/cast');
88
const StrictModeError = require('./error/strict');
99
const Types = require('./schema/index');
1010
const cast$expr = require('./helpers/query/cast$expr');
11+
const castString = require('./cast/string');
1112
const castTextSearch = require('./schema/operators/text');
1213
const get = require('./helpers/get');
1314
const getConstructorName = require('./helpers/getConstructorName');
@@ -89,6 +90,9 @@ module.exports = function cast(schema, obj, options, context) {
8990
val = cast(schema, val, options, context);
9091
} else if (path === '$text') {
9192
val = castTextSearch(val, path);
93+
} else if (path === '$comment' && !schema.paths.hasOwnProperty('$comment')) {
94+
val = castString(val, path);
95+
obj[path] = val;
9296
} else {
9397
if (!schema) {
9498
// no casting for Mixed types

‎lib/schema/operators/text.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const castString = require('../../cast/string');
1515
* @api private
1616
*/
1717

18-
module.exports = function(val, path) {
18+
module.exports = function castTextSearch(val, path) {
1919
if (val == null || typeof val !== 'object') {
2020
throw new CastError('$text', val, path);
2121
}

‎test/cast.test.js

+27
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,33 @@ describe('cast: ', function() {
160160
});
161161
});
162162

163+
it('casts $comment (gh-14576)', function() {
164+
const schema = new Schema({ name: String });
165+
166+
let res = cast(schema, {
167+
$comment: 'test'
168+
});
169+
assert.deepStrictEqual(res, { $comment: 'test' });
170+
171+
res = cast(schema, {
172+
$comment: 42
173+
});
174+
assert.deepStrictEqual(res, { $comment: '42' });
175+
176+
assert.throws(
177+
() => cast(schema, {
178+
$comment: { name: 'taco' }
179+
}),
180+
/\$comment/
181+
);
182+
183+
const schema2 = new Schema({ $comment: Number });
184+
res = cast(schema2, {
185+
$comment: 42
186+
});
187+
assert.deepStrictEqual(res, { $comment: 42 });
188+
});
189+
163190
it('avoids setting stripped out nested schema values to undefined (gh-11291)', function() {
164191
const nested = new Schema({}, {
165192
id: false,

0 commit comments

Comments
 (0)
Please sign in to comment.