【问题标题】:Mongoose unique and custom validationMongoose 独特和自定义验证
【发布时间】:2018-06-11 05:01:15
【问题描述】:

我想为电子邮件添加唯一性错误消息的验证。为此,我使用了插件 mongoose-unique-validator。

这是我的模型

var mongoose = require('mongoose'); //V 3.6.1
var uniqueValidator = require('mongoose-unique-validator');

// User Schema
var UserSchema = mongoose.Schema({
    username: {
        type: String,
        required: true
    },
    email: {
        type: String,
        index: true, 
        unique: true,
        required: true,
        uniqueCaseInsensitive: true 
    },
    password: {
        type: String,
        required: true
    }
});

UserSchema.plugin(uniqueValidator);

如果我尝试保存已经在数据库中的电子邮件,我得到 ValidationError:用户验证失败:电子邮件:错误,预计 email 是唯一的。值:xx.xxx@xx.com 在 ValidationError.inspect (C:\nodeapps\pps\node_modules\mongoose\lib\error\validation.js:57:23)

我需要的是将此错误包装到 ValidationError 中,并在我调用 validate 或 save 时将错误显示在表单中。

有人知道怎么做吗?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我认为您可以像这样调用 User.save:

    let user = new User({
      username: 'username',
      email: 'email',
      password: 'password'
    })
    
    user.save(function (error) {
      if (error) {
        console.log(error.message)
      }
    })
    

    如果在保存用户时发生任何错误,message 字段应该包含错误消息。

    【讨论】:

    • 是的!我在控制台中遇到错误,但我想显示它们。像这样: var errors = req.validationErrors(); if(errors){ res.render('register',{ errors:errors });我需要将此错误包装到 ValidationError 中并在表单中显示错误
    • 我不知道如何显示错误。 User.createUser(newUser, function(err, user){ console.log(err); });
    猜你喜欢
    • 1970-01-01
    • 2020-01-19
    • 2017-09-10
    • 2014-04-06
    • 1970-01-01
    • 2014-05-29
    • 2019-11-27
    • 2015-07-20
    • 1970-01-01
    相关资源
    最近更新 更多