Mongoose 条件要求验证 [英] Mongoose conditional required validation

查看:37
本文介绍了Mongoose 条件要求验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 mongoose 并尝试设置一个自定义验证,如果另一个属性值设置为某个值,则该验证将告知该属性是必需的(即不为空).我正在使用以下代码:

I'm using mongoose and trying to set a custom validation that tells the property shall be required (ie. not empty) if another property value is set to something. I'm using the code below:

thing: {
type: String,
validate: [
    function validator(val) {
        return this.type === 'other' && val === '';
    }, '{PATH} is required'
]}

  • 如果我用 {"type":"other", "thing":""} 保存模型,它会正确失败.
  • 如果我用 {"type":"other", "thing": undefined}{"type":"other", "thing": null} 保存模型{"type":"other"} 永远不会执行验证函数,并将无效"数据写入数据库.
    • If I save a model with {"type":"other", "thing":""} it fails correctly.
    • If I save a model with {"type":"other", "thing": undefined} or {"type":"other", "thing": null} or {"type":"other"} the validate function is never executed, and "invalid" data is written to the DB.
    • 推荐答案

      从 mongoose 3.9.1 开始,您可以将函数传递给架构定义中的 required 参数.这解决了这个问题.

      As of mongoose 3.9.1, you can pass a function to the required parameter in the schema definition. That resolves this problem.

      另见 mongoose 的对话:https://github.com/Automattic/mongoose/issues/941

      See also the conversation at mongoose: https://github.com/Automattic/mongoose/issues/941

      这篇关于Mongoose 条件要求验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆