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

BulkWrite updateOne with filter $elemMatch { $elemMatch: { $in: [] } } throwing TypeError #14678

Closed
2 tasks done
Mattxx10 opened this issue Jun 21, 2024 · 1 comment · Fixed by #14687
Closed
2 tasks done
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@Mattxx10
Copy link

Mattxx10 commented Jun 21, 2024

Prerequisites

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

Mongoose version

8.4.3

Node.js version

20.14.0

MongoDB server version

4.4.13

Typescript version (if applicable)

No response

Description

After upgrading mongoose 7.3.4 -> 7.6.13, we started to experience some TypeErrors with one of our bulkWrite operations. We also tried upgrading to 8.4.3, but we still have been facing the same issues.

Error stack:

TypeError: Cannot read properties of undefined (reading 'schema')
    at SchemaArray.cast$elemMatch (PATH\node_modules\mongoose\lib\schema\array.js:626:59)
    at SchemaArray.castForQuery (PATH\node_modules\mongoose\lib\schema\array.js:572:20)
    at cast (PATH\node_modules\mongoose\lib\cast.js:324:43)
    at PATH\node_modules\mongoose\lib\helpers\model\castBulkWrite.js:100:37
    at PATH\node_modules\mongoose\lib\model.js:3584:37
    at each (PATH\node_modules\mongoose\lib\helpers\each.js:11:5)
    at PATH\node_modules\mongoose\lib\model.js:3584:7
    at new Promise (<anonymous>)
    at Function.bulkWrite (PATH\node_modules\mongoose\lib\model.js:3583:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Steps to Reproduce

Here is a simple script that replicates the error-producing behavior on our backend

const mongoose = require('mongoose');
require('dotenv').config();

(async () => {
  await mongoose.connect(`mongodb://${process.env.HOST}:${process.env.PORT}/${process.env.DB_NAME}`);

  const schema = new mongoose.Schema({
    name: String,
    ids: [String] // problematic type
  });

  const Model = mongoose.model('Test', schema);

  await Model.deleteMany();

  try {
    await Model.bulkWrite([
      {
        updateOne: {
          filter: {
            ids: {
              $elemMatch: {
                $in: ['1']
              }
            }
          },
          update: {
            $set: {
              name: 'test'
            },
            $addToSet: {
              ids: {
                $each: ['1', '2']
              }
            }
          },
          upsert: true
        }
      }
    ], { ordered: true, j: true });
  } catch (error) {
    console.error(error);
  }

  await mongoose.disconnect();
})();

Expected Behavior

CASE 1: Filter-matching document found
EXPECTED: ids that don't already exist in document are added to the array ids.

CASE 2: Filter-matching document not found
EXPECTED: A new document is created

@Mattxx10
Copy link
Author

Mattxx10 commented Jun 21, 2024

Notes:

This fallback behavior was recently added for setting schema:
lib/schema/array.js line 626
const schema = this.casterConstructor.schema ?? context.schema;

The issue arises when cast is called inside castBulkWrite.js with a missing parameter 'context', which would I assume should be model.

op['updateOne']['filter'] = cast(model.schema, op['updateOne']['filter'], {
  strict: strict,
  upsert: op['updateOne'].upsert
});

@vkarpov15 vkarpov15 added the confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. label Jun 24, 2024
@vkarpov15 vkarpov15 added this to the 8.4.4 milestone Jun 24, 2024
vkarpov15 added a commit that referenced this issue Jun 25, 2024
fix: handle casting primitive array with $elemMatch in bulkWrite()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants