Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: cast error when there is an elemMatch in the and clause #14171

Merged
merged 3 commits into from Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/schema/array.js
Expand Up @@ -638,14 +638,14 @@ handle.$and = createLogicalQueryOperatorHandler('$and');
handle.$nor = createLogicalQueryOperatorHandler('$nor');

function createLogicalQueryOperatorHandler(op) {
return function logicalQueryOperatorHandler(val) {
return function logicalQueryOperatorHandler(val, context) {
if (!Array.isArray(val)) {
throw new TypeError('conditional ' + op + ' requires an array');
}

const ret = [];
for (const obj of val) {
ret.push(cast(this.casterConstructor.schema, obj, null, this && this.$$context));
ret.push(cast(this.casterConstructor.schema ?? context.schema, obj, null, this && this.$$context));
}

return ret;
Expand Down
32 changes: 32 additions & 0 deletions test/model.query.casting.test.js
Expand Up @@ -791,6 +791,38 @@ describe('model query casting', function() {
assert.ok(res);
assert.deepStrictEqual(res.map(doc => doc.arr[1].id), ['two', 'three']);
});

it('should not throw a cast error when dealing with an array of objects in combination with $elemMatch and nested $and', async function() {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nits: I couldn't think of an appropriate test name, so I'm open to suggestions.

const testSchema = new Schema({
arr: [Object]
});

const Test = db.model('Test', testSchema);
const obj1 = new Test({ arr: [{ id: 'one', name: 'sample1' }, { id: 'two' }] });
await obj1.save();

const obj2 = new Test({ arr: [{ id: 'two', name: 'sample1' }, { id: 'three' }] });
await obj2.save();

const obj3 = new Test({ arr: [{ id: 'three', name: 'sample1' }, { id: 'four' }] });
await obj3.save();
const res = await Test.find({
arr: {
$elemMatch: {
$and: [
{ name: 'sample1' },
{ $or: [
{ id: 'one' },
{ id: 'two' }
] }
]
}
}
}).sort({ _id: 1 });
assert.ok(res);
assert.equal(res.length, 2);
assert.deepStrictEqual(res.map(doc => doc.arr[1].id), ['two', 'three']);
});
});

function _geojsonPoint(coordinates) {
Expand Down