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: casting an array of objects with $elemMatch #14007

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/schema/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -623,8 +623,8 @@ function cast$elemMatch(val, context) {
discriminators[val[discriminatorKey]] != null) {
return cast(discriminators[val[discriminatorKey]], val, null, this && this.$$context);
}

return cast(this.casterConstructor.schema, val, null, this && this.$$context);
const schema = this.casterConstructor.schema ?? context.schema;
return cast(schema, val, null, this && this.$$context);
}

const handle = SchemaArray.prototype.$conditionalHandlers = {};
Expand Down
27 changes: 26 additions & 1 deletion test/model.query.casting.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,7 @@ 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() {
it('should not throw a cast error when dealing with an array of an array of strings in combination with $elemMatch and $not (gh-13880)', async function() {
const testSchema = new Schema({
arr: [[String]]
});
Expand All @@ -766,6 +766,31 @@ describe('model query casting', function() {
assert(res);
assert(res[0].arr);
});
it('should not throw a cast error when dealing with an array of objects in combination with $elemMatch (gh-13974)', async function() {
const testSchema = new Schema({
arr: [Object]
});

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

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

const obj3 = new Test({ arr: [{ id: 'three' }, { id: 'four' }] });
await obj3.save();

const res = await Test.find({
arr: {
$elemMatch: {
$or: [{ id: 'one' }, { id: 'two' }]
}
}
}).sort({ _id: 1 });
assert.ok(res);
assert.deepStrictEqual(res.map(doc => doc.arr[1].id), ['two', 'three']);
});
});

function _geojsonPoint(coordinates) {
Expand Down