我想创建一个使用以下限制验证下面对象的Mongoose Schema:
代码示例
{
field1: "data",
field2: {
type: "data",
data: "data"
}
}
提前致谢。
答案 0 :(得分:4)
{
field1: "your data",
field2:
{
type:
{
"your data"
},
required:false
}
}
所以一个例子是:
{
field1: String,
field2:
{
type:
{
nestedField1:{type:String,required:true},
nestedField2:String
},
required:false
}
}
如果field2存在,那么将需要nestedField1。
答案 1 :(得分:3)
@Mina Michael的答案对我没有用,但是,当我稍加调整后,它对我有用。我这样尝试过:
{
field1: String,
field2:{
type: new Schema({
nestedField1: {type:Boolean,required:true},
nestedField2: String,
}),
required: false
}
}
答案 2 :(得分:0)
如何使用这种模式将数据插入数据库..主要是那些嵌套字段... employee.namefirst = req.body.namefirst;
//first = req.body.namefirst;
employee.name.middle = req.body.namemiddle;
employee.name.last = req.body.namelast;
答案 3 :(得分:-1)
你的意思可能是这样的:
var Field2Schema = new mongoose.Schema({
type: { type: String, required: true },
data: String
});
var MainSchema = new mongoose.Schema({
field1: String,
field2: Field2Schema
});