我已经开始学习Node.js,有一件事情让我有点困惑,那就是模式验证。
什么才是最佳实践来验证数据并向用户显示自定义错误信息呢?
假设我们有这个简单的模式:
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
值以获取详细信息。虽然不够简洁,但这就是做法。 - JohnnyHK