Skip to content

Unable to use $pull on nested array within discriminated union #14675

Closed
@rpmccarter

Description

@rpmccarter

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

MongoDB server version

6.0.14

Typescript version (if applicable)

5.4.5

Description

It is not possible to perform a $pull on a nested discriminator field using Model.findOneAndUpdate()

Steps to Reproduce

I have created an MRE repo at rpmccarter/mongoose-discriminator-pull-bug-repro that demonstrates the bug. Here is some of the relevant code, taken from index.ts:

const LoginSchema = new Schema({}, { discriminatorKey: 'type', _id: false });
const UserSchema = new Schema({
  name: String,
  login: LoginSchema,
});

UserSchema.path<Schema.Types.Subdocument>('login').discriminator(
  'ssh-key',
  new Schema(
    {
      keys: {
        type: [{
          id: { type: String, required: true },
          publicKey: { type: String, required: true }
        }],
        default: [],
      }
    },
    { _id: false }
  )
);

const User = mongoose.model<User>('User', UserSchema, 'users');

const id = '123-456';

// does not work
await User.findOneAndUpdate(
  { _id: user._id, 'login.type': 'ssh-key' },
  { $pull: { 'login.keys': { id } } },
  { new: true }
);

Expected Behavior

$pull should work on nested array fields when the discriminator is specified.

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

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions