Sub-Schemas on Mongoose without Arrays

倾然丶 夕夏残阳落幕 提交于 2019-12-11 12:26:39

问题


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}
});

回答1:


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
});


来源:https://stackoverflow.com/questions/27553941/sub-schemas-on-mongoose-without-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!