Diosney
Diosney

Reputation: 10590

In Mongoose how declare dynamic Schema

I'm a newbie to Mongoose and in the official documentation I don't found anything related to what I need.

How can I declare a child schema that is dynamic?

For example:

var A = new Schema({
    name        : String,
    subtype     : String,
    description : String
});

var B = new Schema({
    name        : String,
    description : String
});

var C = new Schema({
    name        : String,
    type        : [if(type.value == 'A') then uses Schema-A;
                   if(type.value == 'B') then uses Schema-B;
                  ]
});

Hope it makes sense.

Thanks in advance.

Upvotes: 2

Views: 1407

Answers (2)

neverfox
neverfox

Reputation: 7030

You can set the type of the custom section of the schema as {} and then validate different structures that flow in. See this gist. It isn't as nice as having different Schemas set up for the different cases but it should serve the purpose. Essentially, by setting things up this way, you're essentially saying that that part of the document doesn't have a Schema. Think of Schemas as determinate parts of the document, and the only determinate part here is the placeholder for the dynamic parts.

You could also, I think, create each different structure as a different schema but stored in the same collection, choosing the appropriate schema upfront. I've never tried that but it should be allowed because of the schema-less nature of the underlying MongoDB.

Upvotes: 1

Charles
Charles

Reputation: 11796

Why do you need this ?

In Javascript you don t need to think about the class of an object.

You just need to know the type when you want to initialize it and when you want to search in MongoDB.

Upvotes: 0

Related Questions