验证 Mongoose 中的子文档

pas*_*ine 2 validation mongoose mongodb node.js

我在 Mongoose 中使用架构作为子文档,但我无法在其字段中验证它。
这就是我所拥有的

var SubdocumentSchema = new Schema({
    foo: {
        type: String,
        trim: true,
        required: true
    },
    bar: {
        type: String,
        trim: true,
        required: true
    }
});

var MainDocumentSchema = new Schema({
  name: {
    type: String,
    trim: true,
    required: true
  },
  children: {
    type : [ SubdocumentSchema.schema ],
    validate: arrayFieldsCannotBeBlankValidation
  }
});
Run Code Online (Sandbox Code Playgroud)

我想确保子文档的每个字段都不为空。
我发现无法使用标准方法验证数组,因此我编写了自定义验证函数。现在,我必须手动检查所有字段是否正确且不为空,但在我看来,这并不是一个真正可扩展的解决方案,因此我想知道是否有某种本机方法可以从 MainDocument 触发子文档验证。

Joh*_*yHK 5

在 的定义中children,它应该是[SubdocumentSchema],而不是[SubdocumentSchema.schema]

var MainDocumentSchema = new Schema({
  name: {
    type: String,
    trim: true,
    required: true
  },
  children: {
    type : [ SubdocumentSchema ],
    validate: arrayFieldsCannotBeBlankValidation
  }
});
Run Code Online (Sandbox Code Playgroud)

SubdocumentSchema.schema在您当前的代码中评估为undefinedso Mongoose 没有必要的类型信息来验证 的元素children