Skip to content

Discriminator Method Modifies Schema Argument in Mongoose #14821

Closed

Description

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

Node.js version

20.12.2

MongoDB server version

7.0

Typescript version (if applicable)

No response

Description

When using Mongoose's discriminator method to create a new discriminator from a parent model, the method modifies the schema object passed as an argument. Specifically, it adds fields from the parent model's schema into the discriminator's schema, which is an unexpected and potentially invalid behavior.

Steps to Reproduce

const mongoose = require('mongoose');

// 1. Define a parent model User:

const userSchema = new mongoose.Schema({
  username: String,
  email: String,
});
const User = mongoose.model('User', userSchema);

// 2. Define a discriminator schema adminSchema:

const adminSchema = new mongoose.Schema({
  someOtherPropertyOfAdmin: String,
});

// 3. Create a discriminator:
const Admin = User.discriminator('Admin', adminSchema);

// 4. Observe that the adminSchema has been modified to include fields from the userSchema.
console.log(adminSchema.obj);
console.log(Admin.schema.obj);

image

Expected Behavior

Should the adminSchema remain unmodified after being passed to the discriminator method? We expect the fields from the userSchema to be combined with the adminSchema internally by Mongoose, without affecting the original schema object passed as an argument.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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