5
我已经开始学习Node.js,并且有一点让我感到有点困惑,那就是Schema验证。验证Mongoose 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: { : \"[email protected]\" }",
"op": {
"password": "xxx",
"email": "[email protected]",
"_id": "56895e48c978d4a10f35666a",
"__v": 0
}
这是所有有点乱,我想显示发送到客户端方面就像这样:
"status": {
"text": "Email [email protected] is already taken.",
"code": 400
}
如何做到这一点?
键入11000的“code”值,然后解析errmsg值以获取详细信息。没有你想要的那么干净,但这就是你如何去做的。 – JohnnyHK