Skip to content

Recompiling schema does not reapply discriminators #14444

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

8.2.2

Node.js version

18.16

MongoDB server version

6.3.0

Typescript version (if applicable)

No response

Description

I have a use case where I define a schema that uses a discriminated schema in a base package. I want to enable dependent packages to add their own implementations of the discriminated schema. However, it seems that once the model that uses the schema is compiled, adding further discriminated schemas are not applied.

Steps to Reproduce

'use strict';

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

// Define discriminated schema
const decoratorSchema = new Schema({
    type: { type: String, required: true },
}, { discriminatorKey: "type" });

class Decorator {
    type;
    whoAmI() { return "I am BaseDeco"; }
}
decoratorSchema.loadClass(Decorator);

// Define discriminated class before model is compiled
class Deco1 extends Decorator { whoAmI() { return "I am Deco1"; }};
const deco1Schema = new Schema({}).loadClass(Deco1);
deco1Schema.loadClass(Deco1);
decoratorSchema.discriminator("Deco1", deco1Schema);

// Define model that uses discriminated schema
const shopSchema = new Schema({
    item: { type: decoratorSchema, required: true }
});

class Shop {};
shopSchema.loadClass(Shop);
const shopModel = mongoose.model("shop", shopSchema);

// Define another discriminated class after the model is compiled
class Deco2 extends Decorator { whoAmI() { return "I am Deco2"; }};
const deco2Schema = new Schema({}).loadClass(Deco2);
deco2Schema.loadClass(Deco2);
decoratorSchema.discriminator("Deco2", deco2Schema);

// Shouldn't recompiling the schema fix this?
shopModel.recompileSchema();

void async function main() 
{
    let instance = new shopModel({ item: {type: "Deco1"} }); // "I am Deco1" - Works
    console.log(instance.item.whoAmI());

    instance = new shopModel({ item: {type: "Deco2"} }); // "I am BaseDeco" - Should be Deco2
    console.log(instance.item.whoAmI());
}();

Expected Behavior

After recompiling a schema, it should also apply new discriminators of its fields.

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