Skip to content

schema.recompileSchema exception when subDocument discriminator is defined before the model is compiled #14527

@ZachLeviPixel

Description

@ZachLeviPixel

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

Node.js version

18.16

MongoDB server version

6.3.0

Typescript version (if applicable)

No response

Description

The following example throws "discriminator with name 'X' already exists" when the model of the top level schema is compiled after the discriminator definitions have been created on the subdocument schema.

If you create the model first, recompile seems to work as expected.
Important to note that on either case, the schema behaves as expected without recompiling.

Steps to Reproduce

const mongoose = require("mongoose");

const shopItemSchema = new mongoose.Schema({}, { discriminatorKey: "type" });
const shopSchema = new mongoose.Schema({
    items: { type: [shopItemSchema], required: true },
});

const shopItemSubType = new mongoose.Schema({});
// const shopModel = mongoose.model("shop", shopSchema); // If the shop model is created before the schema is discriminated, recompile will work
shopItemSchema.discriminator(2, shopItemSubType);
const shopModel = mongoose.model("shop", shopSchema);

shopModel.recompileSchema(); // Error: Discriminator with name "2" already exists

Expected Behavior

The schema should recompile without error.

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