Skip to content

Add discriminator key to findOneAndUpdate #6087

@JonathanZWhite

Description

@JonathanZWhite

Do you want to request a feature or report a bug?
Feature

What is the current behavior?
If I have the following discriminators:

const messageSchema = new Schema({ text: String });
const Message = mongoose.model('Message', messageSchema);

/* ============ */

const attachmentMessageSchema = new Schema({
  type: { type: String, default: 'ATTACHMENT' },
  attachment: String,
});

const AttachmentMessage = Message.discriminator(
  'AttachmentMessage',
  attachmentMessageSchema,
);

In order to update an instance of AttachmentMessage I would have to write AttachmentMessage.findOneAndUpdate. If I write Message.findOneAndupdate no changes will occur.

I think this is because the discriminator key is only added to find(), count(), and aggregate. As the docs state:

Discriminator models are special; they attach the discriminator key to queries. In other words, find(), count(), aggregate(), etc. are smart enough to account for discriminators.

However, there are cases where the server might not be aware of the discriminator type of the model I want to update. For example, the client might pass a generic message payload:

{
  text: 'some_text',
  attachment: <payload>
}

Ideally, it would be nice to be able to pass that payload to the following function:

updateMessage(id, data) {
  return Message.findByIdAndUpdate(id, data, {
    new: true,
  });
}

Could we automatically add the discriminator key to functions like findOneAndUpdate to address these cases? I saw a PR in Mongoose Schema extended that seems to model the desired behavior: https://github.com/briankircho/mongoose-schema-extend/pull/53/files

Please mention your node.js, mongoose and MongoDB version.
Node: 8.4.0
Mongo: 3.0.7
Mongoose: 4.4.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsThis issue is due to a mistake or omission in the mongoosejs.com documentation

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions