Skip to content

$switch in $expr in filter query failed: Cannot read properties of undefined (reading 'map') #14751

@eherve

Description

@eherve

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

7.6.3

Node.js version

20.11.1

MongoDB server version

7

Typescript version (if applicable)

5.1

Description

when using $switch in filter in query, mongoose throw a type error:

TypeError: Cannot read properties of undefined (reading 'map')
        at _castExpression (node_modules/mongoose/lib/helpers/query/cast$expr.js:96:18)
        at castComparison (node_modules/mongoose/lib/helpers/query/cast$expr.js:213:12)
        at _castExpression (node_modules/mongoose/lib/helpers/query/cast$expr.js:105:18)
        at node_modules/mongoose/lib/helpers/query/cast$expr.js:103:36
        at Array.map (<anonymous>)
        at _castExpression (node_modules/mongoose/lib/helpers/query/cast$expr.js:103:27)
        at cast$expr (node_modules/mongoose/lib/helpers/query/cast$expr.js:75:10)
        at cast (node_modules/mongoose/lib/cast.js:92:13)
        at model.Query.Query.cast (node_modules/mongoose/lib/query.js:4909:12)
        at model.Query.Query._castConditions (node_modules/mongoose/lib/query.js:2232:10)

in the cast$expr.js file, when the presence of $switch is checked, there is an issue with the branches and default check :

  else if (val.$switch != null) {
    val.branches.map(v => _castExpression(v, schema, strictQuery));
    val.default = _castExpression(val.default, schema, strictQuery);
  }

val.$switch is defined but next lines the values used are val.branches and val.default and they are undefined.
Te values should be val.$switch.branches and val.default

Steps to Reproduce

model.find({
  $expr: {
    $eq: [
      {
        $switch: {
          branches: [{case: {$eq: ['$$NOW', '$$NOW']}, then: true}],
          default: false,
        },
      },
      true,
    ],
  },
});

throw the error, but using te collection it does not

model.collection.find({
  $expr: {
    $eq: [
      {
        $switch: {
          branches: [{case: {$eq: ['$$NOW', '$$NOW']}, then: true}],
          default: false,
        },
      },
      true,
    ],
  },
}).toArray();

Expected Behavior

Should work as it does when using the collection instead of te mongoose model

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions