Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongoose-创建父文档时如何要求子文档数据?_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js Mongoose-创建父文档时如何要求子文档数据?

Node.js Mongoose-创建父文档时如何要求子文档数据?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我刚刚开始使用Mongoose(v3.8.1),正在试验子文档和验证。据我所知(从本页底部:),以下是设置架构的正确方法: var ParentSchema = new Schema({ name: { type: String, required: true }, children: [{ name: { type: String, required: true } }] }); 然后,我可以执行以下操作来创建文档/子文档: ParentModel.c

我刚刚开始使用Mongoose(v3.8.1),正在试验子文档和验证。据我所知(从本页底部:),以下是设置架构的正确方法:

var ParentSchema = new Schema({
    name: { type: String, required: true },
    children: [{
        name: { type: String, required: true }
    }]
});
然后,我可以执行以下操作来创建文档/子文档:

ParentModel.create({
    name: "Parent 1",
    children: [
        { name: "Child 1" },
        { name: "Child 2" },
    ]
}, callback);
这非常有效,如果省略任何子名称,验证就会失败。但是,如果我完全省略了
子项
键,验证将通过,并插入一个空数组


因此,如果省略了
子项
键,是否有办法触发验证错误?或者我是否以错误的方式进行了此操作?

在进行了更多的操作之后,我想我已经得到了它!使用
type
键指定架构,我还可以设置
required:true
。看来现在可以用了

更新的架构:

var ParentSchema = new Schema({
    name: { type: String, required: true },
    children: {
        type: [{
            name: { type: String, required: true }
        }],
        required: true
    }
});