diff --git a/lib/helpers/query/cast$expr.js b/lib/helpers/query/cast$expr.js index a13190b1c41..efa2cace344 100644 --- a/lib/helpers/query/cast$expr.js +++ b/lib/helpers/query/cast$expr.js @@ -92,8 +92,12 @@ function _castExpression(val, schema, strictQuery) { } else if (val.$ifNull != null) { val.$ifNull.map(v => _castExpression(v, schema, strictQuery)); } else if (val.$switch != null) { - val.branches.map(v => _castExpression(v, schema, strictQuery)); - val.default = _castExpression(val.default, schema, strictQuery); + if (Array.isArray(val.$switch.branches)) { + val.$switch.branches = val.$switch.branches.map(v => _castExpression(v, schema, strictQuery)); + } + if ('default' in val.$switch) { + val.$switch.default = _castExpression(val.$switch.default, schema, strictQuery); + } } const keys = Object.keys(val); diff --git a/test/helpers/query.cast$expr.test.js b/test/helpers/query.cast$expr.test.js index 416db9af5c6..fd3f7cd5bfe 100644 --- a/test/helpers/query.cast$expr.test.js +++ b/test/helpers/query.cast$expr.test.js @@ -118,4 +118,33 @@ describe('castexpr', function() { res = cast$expr({ $eq: [{ $round: ['$value'] }, 2] }, testSchema); assert.deepStrictEqual(res, { $eq: [{ $round: ['$value'] }, 2] }); }); + + it('casts $switch (gh-14751)', function() { + const testSchema = new Schema({ + name: String, + scores: [Number] + }); + const res = cast$expr({ + $eq: [ + { + $switch: { + branches: [{ case: { $eq: ['$$NOW', '$$NOW'] }, then: true }], + default: false + } + }, + true + ] + }, testSchema); + assert.deepStrictEqual(res, { + $eq: [ + { + $switch: { + branches: [{ case: { $eq: ['$$NOW', '$$NOW'] }, then: true }], + default: false + } + }, + true + ] + }); + }); });