Skip to content

Commit

Permalink
fix: handle casting $elemMatch underneath $not underneath another…
Browse files Browse the repository at this point in the history
… `$elemMatch`

Fix #13880
  • Loading branch information
vkarpov15 committed Sep 25, 2023
1 parent d8429aa commit 3dc87cb
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ module.exports = {
'*.min.js',
'**/docs/js/native.js',
'!.*',
'node_modules'
'node_modules',
'.git'
],
overrides: [
{
Expand Down
18 changes: 16 additions & 2 deletions lib/cast.js
Original file line number Diff line number Diff line change
Expand Up @@ -309,8 +309,21 @@ module.exports = function cast(schema, obj, options, context) {
while (k--) {
$cond = ks[k];
nested = val[$cond];

if ($cond === '$not') {
if ($cond === '$elemMatch') {
if (nested && schematype != null && schematype.schema != null) {
cast(schematype.schema, nested, options, context);
} else if (nested && schematype != null && schematype.$isMongooseArray) {
if (utils.isPOJO(nested) && nested.$not != null) {
cast(schema, nested, options, context);
} else {
val[$cond] = schematype.castForQuery(
$cond,
nested,
context
);
}
}
} else if ($cond === '$not') {
if (nested && schematype) {
_keys = Object.keys(nested);
if (_keys.length && isOperator(_keys[0])) {
Expand All @@ -337,6 +350,7 @@ module.exports = function cast(schema, obj, options, context) {
context
);
}

}
}
} else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) {
Expand Down
12 changes: 12 additions & 0 deletions test/model.query.casting.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,18 @@ describe('model query casting', function() {
assert.strictEqual(doc.outerArray[0].innerArray[0], 'onetwothree');
});
});
it('should not throw a cast error when dealing with an array of an array of strings in combination with $elemMach and $not (gh-13880)', async function() {
const testSchema = new Schema({
arr: [[String]]
});
const Test = db.model('Test', testSchema);
const doc = new Test({ arr: [[1, 2, 3], [2, 3, 4]] });
await doc.save();
const query = { arr: { $elemMatch: { $not: { $elemMatch: { $eq: '1' } } } } };
const res = await Test.find(query);
assert(res);
assert(res[0].arr);
});
});

function _geojsonPoint(coordinates) {
Expand Down

0 comments on commit 3dc87cb

Please sign in to comment.