【问题标题】:Validate subdocuments in Mongoose在 Mongoose 中验证子文档
【发布时间】:2014-09-15 00:43:57
【问题描述】:

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

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

【问题讨论】:

  • 我很高兴看到你的验证函数arrayFieldsCannotBeBlankValidation 它会验证数组中的每个对象吗?例如:它会用MainDocumentSchema.children.name 检查任何重复值吗?
  • 我真的不记得了,代码已经很久以前了。对不起!

标签: node.js mongodb validation mongoose


【解决方案1】:

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

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

SubdocumentSchema.schema 的计算结果为 undefined,因此在您当前的代码中,Mongoose 没有必要的类型信息来验证 children 的元素。

【讨论】:

  • 谢谢伙计。我把所有试图在数组上运行自定义验证的事情都搞砸了,以为问题就在那里,而我调用模式的方式却是这样。你救了我。
猜你喜欢
  • 2019-06-03
  • 1970-01-01
  • 2014-08-27
  • 2015-09-30
  • 2018-10-31
  • 2020-05-22
  • 2012-09-11
  • 2018-04-15
  • 2019-12-09
相关资源
最近更新 更多