2017-03-27 187 views
2

我已经定义了以下猫鼬架构需要子文档猫鼬

var subSchema = new Schema({ 
    propertySub: {type: String, required: true} 
}); 

var mainSchema = new Schema({ 
    mainProperty: {type: String, required: true}, 
    subs: [subSchema] 
}); 

正如你可以看到有关于subSchema必需的属性,而问题是,我想一个mainSchema被要求至少有一个subSchema ,但是当我发送一个

{ 
    "mainProperty" : "Main" 
} 

没有失败。

我想是这样

subs: [{ 
    type: subSchema, 
    required: true 
}] 

但它抛出如下:

TypeError: Undefined type undefined at array subs

所以无论如何与validate我是新做这个?也许到节点和猫鼬这样的解释会不胜感激

回答

2

是的,你会要么使用验证,或者如果你想要使用预存钩子验证。这里有一个使用验证的例子

var mainSchema = new Schema({ 
    mainProperty: {type: String, required: true}, 
    subs: { 
     type: [subSchema], 
     required: true, 
     validate: [notEmpty, "Custom error message"] 
    } 
}); 

function notEmpty(arr) { 
    return arr.length > 0; 
}