node.js - 验证 Mongoose 中的子文档

标签 node.js mongodb validation mongoose

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

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

最佳答案

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 的元素.

关于node.js - 验证 Mongoose 中的子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24917143/

相关文章:

javascript - 检查 ASP.Net 验证器客户端的结果

javascript - 使用 jquery 验证插件逐步验证

node.js - 原子壳( Electron )是否可以使用系统级API?

javascript - Grunt 构建导致 Angular 应用程序在 dist 上崩溃

macos - mac上mongodb数据库的位置

javascript - 从 node.js 的 mongodb 集合中删除文档

javascript - 将对象推送到 Node.js 中全局声明的数组中

javascript - 生成 PDF 和 Excel 工作表,但在 Excel 中它既不打开也不选择保存....(就像在 Laravel 中一样)

mongoDB 获取数组的最新日期

jQuery 验证错误(元素未定义)