Skip to content

Arrayfilters does not work with nested array with descriminator #15386

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

Open
2 tasks done
emmet-opinionx opened this issue Apr 30, 2025 · 1 comment · May be fixed by #15388
Open
2 tasks done

Arrayfilters does not work with nested array with descriminator #15386

emmet-opinionx opened this issue Apr 30, 2025 · 1 comment · May be fixed by #15388
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@emmet-opinionx
Copy link

emmet-opinionx commented Apr 30, 2025

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.14.1

Node.js version

20.18.0

MongoDB server version

5

Typescript version (if applicable)

No response

Description

If you have a array of documents on a discriminated schema array. mongoose fails to find the correct schema when casting array filters

Steps to Reproduce

The following throws error Could not find path "events.0.products.0._id" in schema

  const eventSchema = new Schema(
    { message: String },
    { discriminatorKey: 'kind', _id: false },
  );

  const batchSchema = new Schema({ events: [eventSchema] });

  // `batchSchema.path('events')` gets the mongoose `DocumentArray`
  // For TypeScript, use `schema.path<Schema.Types.DocumentArray>('events')`
  const docArray = batchSchema.path<Schema.Types.DocumentArray>('events');

  // The `events` array can contain 2 different types of events, a
  // 'clicked' event that requires an element id that was clicked...
  const clickedSchema = new Schema(
    {
      element: {
        type: String,
        required: true,
      },
    },
    { _id: false },
  );
  // Make sure to attach any hooks to `eventSchema` and `clickedSchema`
  // **before** calling `discriminator()`.
  docArray.discriminator('Clicked', clickedSchema);

  const productSchema = new Schema({
    name: { type: String },
    price: { type: Number },
  });

  // ... and a 'purchased' event that requires the product that was purchased.
  docArray.discriminator(
    'Purchased',
    new Schema({
      products: {
        type: [productSchema],
        required: true,
      },
    }),
  );

  const Batch = db.model('EventBatch', batchSchema);

  const purchasedId = new mongoose.Types.ObjectId();
  const productId = new mongoose.Types.ObjectId();

  const doc = await Batch.create({
    events: [
      { kind: 'Clicked', element: '#hero', message: 'hello' },
      {
        kind: 'Purchased',
        _id: purchasedId,
        products: [{ name: 'productName1', price: 10, _id: productId }],
        message: 'world',
      },
    ],
  });

  console.log('Result', doc);

  const updatedBatch = await Batch.findByIdAndUpdate(
    doc._id,
    {
      'events.$[event].products.$[product].price': 20,
    },
    {
      arrayFilters: [
        {
          'event._id': purchasedId,
          'event.kind': 'Purchased', // Does not work with or without this
        },
        { 'product._id': productId },
      ],
      new: true,
    },
  ).exec();

Expected Behavior

Should be able to use arrayFilters to update an array on nested array of a discriminated schema

@emmet-opinionx emmet-opinionx changed the title Arrayfilters does not work with nested array on with descriminator Arrayfilters does not work with nested array with descriminator Apr 30, 2025
@vkarpov15 vkarpov15 added the confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. label Apr 30, 2025
vkarpov15 added a commit that referenced this issue Apr 30, 2025
@vkarpov15 vkarpov15 added this to the 8.14.2 milestone Apr 30, 2025
@vkarpov15
Copy link
Collaborator

We have a fix in #15388 that we will deploy later this week. For #15388 to work, you'll have to specify the discriminator key in the event array filter as follows - this is consistent with other parts of the Mongoose API where you need to explicitly specify the discriminator key for updates to respect the discriminator key.

  const updatedBatch = await Batch.findByIdAndUpdate(
    doc._id,
    {
      'events.$[event].products.$[product].price': 20,
    },
    {
      arrayFilters: [
        {
          'event._id': purchasedId,
          'event.kind': 'Purchased', // <-- make sure this line is set
        },
        { 'product._id': productId },
      ],
      new: true,
    },
  ).exec();

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
2 participants