aosh5
aosh5

Reputation: 89

Mongoose Schema with different objects

I have a base schema that looks like that:

let Entry = new Schema({
key: String,
items: [
    {
        id: Number,
        text: String
    }
]});

But the item schema can vary, I want that I can append new object that have the same schema like the the base schema. So that an object in items can also have own items. Example:

let Entry = new Schema({
key: String,
items: [
    {
        id: Number,
        text: String
    },
    {
        key: String,
        items: [
            ...
        ]
    }
]
});

And so on... so that I can have maybe 4 normal item objects with id and text, or maybe also nested objects in items, which again have key and items[...] properties, with the possibility to repeat the process even further.

Upvotes: 0

Views: 1406

Answers (1)

Lee Brindley
Lee Brindley

Reputation: 6472

One method would be to utilise the Mixed type from Mongoose.

Say something like this:

let Entry = new Schema({
key: String,
items: [
    {
        id: Number,
        text: String,
        data: {
            type: Schema.Types.Mixed,
            default: {}
        }
    }
]});

Now this example places any 'custom' fields inside a data property, unsure if that would suffice for your needs.

Usage

const newEntry = new Entry({
    id: 1,
    text: "foobar",
    data: {
        hello: "world",
        isCorrect: true
    }
});

Alternatively, you could just set strict to false on the schema.

let Entry = new Schema({
key: String,
items: [
    {
        id: Number,
        text: String
    }
]}, { strict: false});

Usage

const newEntry = new Entry({
    id: 1,
    text: "foobar",
    hello: "world",
    isCorrect: true
});

My personal preference would be the first option, at least this way, looking at the schema, I know that there is a mixed 'bag' of data in each record, contained within the 'data' field. Both are documented methods defined within the mongoose documentation, and hence perfectly valid. Pick your poison :)

Refs:

Mixed Schema Type documentation:

https://mongoosejs.com/docs/schematypes.html#mixed

strict Schema option documentation:

https://mongoosejs.com/docs/guide.html#strict

Upvotes: 1

Related Questions