【问题标题】:How to ensure Mongoose schema structure如何确保 Mongoose 架构结构
【发布时间】:2013-12-16 05:15:03
【问题描述】:

使用 Mongoose,我们可以确保 叶路径 属于特定类型:new Schema({name: String})user.name = {} 将无法通过验证。很好。

但是现在假设我将架构更改为new Schema({name: {first:String, last:String}})。运行 user.name="Tyler";user.save() 验证就好了。似乎架构完整性验证仅适用于叶路径,不适用于根/中间路径(又名,不适用于架构结构

这里有触发验证错误的方法吗?

【问题讨论】:

  • 顺便说一句,这也不起作用:schema.path('name').validate(function(v){ return typeof v === 'object' }, err)。抛出Cannot call method 'validate' of undefined

标签: mongoose


【解决方案1】:

Mongoose 还支持除叶子类型之外的更多模式验证,详情请参阅here

Mongoose 有几个内置的验证器。

  • 所有 SchemaType 都有内置的必需验证器
  • 数字有最小和最大验证器
  • 字符串具有枚举和匹配验证器

即所需的验证器可用于解决问题中描述的问题:

new Schema({
    name: {
        first: {
            type: String,
            required: true
        } , 
        last: {
            type: String,
            required:true
        }
     }
})

如果内置验证不充分,那么也可以编写自定义验证器,例如使用mongoose-validator

【讨论】:

  • required 的想法很好。我想了想,试过了,它奏效了——然后又放弃了“这不可能是正确的方法”的想法。现在你提到它,我想得更彻底,我认为这实际上是一个相当不错的方法。
猜你喜欢
  • 2016-02-29
  • 2022-01-23
  • 1970-01-01
  • 2016-10-27
  • 2014-10-03
  • 2019-07-26
  • 2021-03-09
  • 2014-09-14
  • 2013-02-09
相关资源
最近更新 更多