Bakbok
Bakbok

Reputation: 33

Sub-Schemas on Mongoose without Arrays

So, I was wondering, even though I understood that you cannot create a single sub-document, I still would like to create a sub-document so that I can use default and other mongoose types properly, is there a way to still do such a thing?

for example :

var SomeOtherScheme = new Schema({
a              : { type:String, default:'test' },
b              : { type:Boolean, default:false }
...
});

var GroupSettings = new Schema({
x              : { type:Number, default:20 },
y              : { type:Boolean, default:false },
...
else           : { type:SomeOtherScheme, default:SomeOtherScheme }
});

var Group = new Schema({
name                : { type:String , required:true, unique:true},
description         : { type:String, required:true },
...
settings            : {type:GroupSettings,default:GroupSettings}
});

Upvotes: 1

Views: 216

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312115

The schema of embedded objects need to be defined using plain objects, so if you want to keep the definitions separate you can do it as:

var SomeOther = {
    a              : { type:String, default:'test' },
    b              : { type:Boolean, default:false }
    ...
};
var SomeOtherSchema = new Schema(SomeOther); // Optional, if needed elsewhere

var GroupSettings = {
    x              : { type:Number, default:20 },
    y              : { type:Boolean, default:false },
    ...
    else           : SomeOther
};
var GroupSettingSchema = new Schema(GroupSettings); // Optional, if needed elsewhere

var GroupSchema = new Schema({
    name                : { type:String , required:true, unique:true},
    description         : { type:String, required:true },
    ...
    settings            : GroupSettings
});

Upvotes: 1

Related Questions