猫鼬验证:必需:false,验证:regex,空值问题 [英] Mongoose validation: required : false, validate : regex, issues with empty values

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

问题描述

我从猫鼬验证中收到此消息:

I get this message from Mongoose validation:

验证程序失败,路径电话的值为''

'Validator failed for path phone with value ``'

不应该这样,因为不需要电话.

That shouldn't happen since phone is not required.

这是我的模型架构:

var user = new Schema(
{ 
    _id      : { type: String, required: true },
    name     : { type: String, required: true},
    phone    : { type: String, required: false, validate: /^\d{10}$/ },
    password : { type: String },
    added    : { type: Date,    default: Date.now },
},
{collection : 'users'}
);

当我使用required: false并设置validate属性时,似乎猫鼬的验证失败. 如果我将其更改为:

It seems that mongoose's validation fails when i use required: false and set validate property up. If I change it to:

phone    : { type: String, required: false},

一切正常,为什么呢? 我在做什么错了?

Everything goes right, why is that? What am I doing wrong?

推荐答案

您可以尝试使用自定义验证程序,因为它们仅在给定键上有值时才触发,因为自定义验证的键选择是通过:

You may try with a custom validator as they are only triggered when there is a value on a given key because the key selection for custom validation is done via path() :

var user = new Schema({

  // ...
  phone    : { type: String }, // using default - required:false
  // ...

});

// Custom validation
user.path('phone').validate(function (value) {

  // Your validation code here, should return bool

}, 'Some error message');

看看这个问题:为什么猫鼬不验证空文件?

这还将有效地防止文档在验证失败的情况下持久保存到数据库中,除非您相应地处理错误.

This will also effectively prevent the document to be persisted to the DB if validation fails, unless you handle the error accordingly.

BonusTip: 尝试以一种简单的方式进行自定义验证,例如,尽量避免循环,并避免在in中使用lodash或下划线根据我的经验,我发现在处理大量事务时,这些性能成本可能会很高.

这篇关于猫鼬验证:必需:false,验证:regex,空值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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