Skip to content

fix(query): avoid casting logical operators in $elemMatch against the parent schema - #16761

Open
MFA-G wants to merge 1 commit into
Automattic:masterfrom
MFA-G:fix/elem-match-logical-operators-no-embedded-schema
Open

MFA-G wants to merge 1 commit into
Automattic:masterfrom
MFA-G:fix/elem-match-logical-operators-no-embedded-schema

Conversation

@MFA-G

@MFA-G MFA-G commented Nov 26, 2026

Copy link
Copy Markdown

Summary

$or, $and, and $nor clauses inside $elemMatch on an array whose items have no schema ([Mixed], [String], Array, ...) are currently cast against the parent document schema. With strictQuery enabled this strips the clause fields ($or: [{}, {}]), casts fields that happen to share a name with a parent path (which can throw), and bulkWrite() throws TypeError: Cannot read properties of undefined (reading 'schema') because there is no query context.

These arrays have no item schema, so their $elemMatch clauses are arbitrary objects rather than subdocument paths. This change leaves the clauses as-is, matching Mongoose 6.x behavior. Document arrays still cast clause fields against their subdocument schema.

Fixes #16754.

Examples

mongoose.set('strictQuery', true);

const Job = mongoose.model('Job', new mongoose.Schema({
  name: String,
  params: [mongoose.Schema.Types.Mixed]
}));

const filter = {
  params: { $elemMatch: { $or: [{ programId: 'p1' }, { program: 'Program A' }] } }
};

Job.find(filter).cast(Job);
// before: { params: { $elemMatch: { $or: [{}, {}] } } }
// after:  { params: { $elemMatch: { $or: [{ programId: 'p1' }, { program: 'Program A' }] } } }

Tests

Added regression tests for $or/$and/$nor on [Mixed], [String], and bare Array paths, for document arrays (still cast), and for bulkWrite() filter casting.

  • npx mocha --exit test/model.query.casting.test.js — 54 passing
  • npx mocha --exit test/query.test.js test/model.query.casting.test.js — 404 passing
  • npx mocha --exit test/model.test.js --grep bulkWrite — 45 passing
  • ESLint on all changed files

… parent schema

Arrays whose items have no schema ([`Mixed`], [`String`], `Array`, ...) have no embedded schema to cast $or/$and/$nor clauses against. The fallback used the parent document schema, so with strictQuery enabled Mongoose stripped the clause fields, cast fields that happened to share a name with a parent path, and bulkWrite() threw because there is no query context. Leave these clauses as-is, like Mongoose 6.x did. Clauses in document arrays are still cast against the subdocument schema.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

$or/$and/$nor inside $elemMatch on arrays without an item schema are cast against the parent schema (stripped by strictQuery)

1 participant