【问题标题】:Best practice to validate Mongoose Schema and display custom error message验证 Mongoose Schema 并显示自定义错误消息的最佳实践
【发布时间】:2016-04-07 09:32:57
【问题描述】:

我已经开始学习 Node.js,而让我有点困惑的一件事是 Schema 验证。

验证数据并向用户显示自定义错误消息的最佳做法是什么?

假设我们有这个简单的架构:

var mongoose = require("mongoose");

// create instance of Schema
var Schema = mongoose.Schema;

// create schema
var Schema  = {
    "email" : { type: String, unique: true },
    "password" : String,
    "created_at" : Date,
    "updated_at" : Date
};

// Create model if it doesn't exist.
module.exports = mongoose.model('User', Schema);

我希望注册用户拥有独特的电子邮件,因此我已将unique: true 添加到我的架构中。现在,如果我想向用户显示错误消息,说明他为什么没有注册,我会收到如下响应:

    "code": 11000,
    "index": 0,
    "errmsg": "E11000 duplicate key error index: my_db.users.$email_1 dup key: { : \"test@test.com\" }",
    "op": {
      "password": "xxx",
      "email": "test@test.com",
      "_id": "56895e48c978d4a10f35666a",
      "__v": 0
    }

这有点乱,我想显示发送到客户端,就像这样:

"status": {
  "text": "Email test@test.com is already taken.",
  "code": 400
}

如何做到这一点?

【问题讨论】:

  • 关闭code值11000,然后解析errmsg值以获取详细信息。没有你想要的那么干净,但你就是这样做的。

标签: node.js mongodb mongoose mongoose-schema


【解决方案1】:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const { hash } = require('../helpers/bcrypt')

const userSchema = new Schema({

email: {
    type: String,
    required: [true, 'email is required'],
    match: [/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/, 'Invalid email format'],
    validate: {
        validator: function(v){
            return this.model('User').findOne({ email: v }).then(user => !user)
        },
        message: props => `${props.value} is already used by another user`
    },
},
password: {
    type: String,
    required: [true, 'password is required']
}

})

userSchema.pre('save', function(done){
    this.password = hash(this.password)
    done()
})


module.exports = mongoose.model('User', userSchema)

【讨论】:

    【解决方案2】:

    处理 mongoose 中唯一约束的错误消息的最简单方法是使用插件,例如 mongoose-beautiful-unique-validation。它使错误消息看起来像普通的验证错误消息。

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 2010-10-12
      • 1970-01-01
      • 2021-08-11
      • 2018-02-08
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多