Home > Mobile >  How can I use an enum of multiple Schemas and have a default in Mongoose
How can I use an enum of multiple Schemas and have a default in Mongoose

Time:06-16

I want to be able to have a field where its type is one of a list of Schemas (or objects) and with one working as a default.

In my head it would look like this (but this doesn't work):

const fooSchema = new mongoose.Schema({
    // ...
});

const barSchema = new mongoose.Schema({
    // ...
});

const modelSchema = new mongoose.Schema({
    field: {
        type: mongoose.Schema.Types.Mixed,
        enum: [fooSchema, barSchema],
        default: fooSchema,
        required: true
    }
});

How would I go about achieving this? Should I be approaching it differently?

CodePudding user response:

I have found that discriminators helped accomplish this goal. I retrieved this information through this comment and this post. Below is an example implementation for anyone else that comes across this problem.

// Type Base

const baseOptions = {
    discriminatorKey: 'kind',
    _id: false
}

const baseSchema = new mongoose.Schema({

    kind: {
        type: String,
        enum: ['foo', 'bar'],
        required: true
    }

    // ...
}, baseOptions );

// Types

const fooSchema = new mongoose.Schema({
    // ...
}, { _id: false });

const barSchema = new mongoose.Schema({
    // ...
}, { _id: false });

// Main Model

const modelSchema = new mongoose.Schema({
    field: {
        type: baseSchema,
        default: {
            kind: 'foo'
        },
        required: true
    }
});

modelSchema.path( 'field' ).discriminator( 'foo', fooSchema );
modelSchema.path( 'field' ).discriminator( 'bar', barSchema );

const Model = mongoose.model( 'Model', modelSchema );
  • Related