Skip to content

Error on defining more than one self-referencing discriminated schema #15120

@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.9.1, 8.7.3

Node.js version

18.16.0

MongoDB server version

4.8.1

Typescript version (if applicable)

No response

Description

Defining more than one discriminated schema causes an Error: Discriminator with name already exists

Steps to Reproduce

'use strict';

const mongoose = require('mongoose');
const { Schema } = mongoose;

const baseSchema = new Schema({
    type: { type: Number, required: true },
}, { discriminatorKey: "type" });

const selfRefSchema = new Schema({
    self: { type: [baseSchema] },
});

const anotherSelfRefSchema = new Schema({
    self2: { type: [baseSchema] },
});

baseSchema.discriminator(5, selfRefSchema);
baseSchema.discriminator(6, anotherSelfRefSchema); // Commenting this line make the script work
mongoose.model("base", baseSchema); // Error: Discriminator with name "5" already exists

Expected Behavior

Should be able to define any number of schemas that self reference.

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