【发布时间】:2019-02-13 09:57:46
【问题描述】:
我创建了电子邮件和用户名是唯一的用户架构。当我尝试使用集合中已存在的用户名保存用户时,MongoDb(mongoose 驱动程序)返回以下错误。
"error": {
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: todo.users index: username_1 dup key: { : \"sak\" }"
}
但是当我尝试使用集合中已经存在的电子邮件地址保存用户时,MongoDb(猫鼬驱动程序)会返回相同类型的错误,就像这样。
"error": {
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: todo.users index: email_1 dup key: { : \"sachin121@gmail.com\" }"
}
这是我的用户架构 -
const UserSchema = new mongoose.Schema(
{
email: {
type: String,
lowercase: true,
trim: true,
index: true,
unique: true,
required: true
},
username: {
type: String,
lowercase: true,
trim: true,
index: true,
unique: true,
required: true
},
password: {
type: String,
required: true,
bcrypt: true
},
name: {
type: String,
trim: true,
required: true
}
});
【问题讨论】:
-
这是预期的行为。您的错误类型是
duplicate key,因为这两个字段都标记为唯一索引。查看显示失败的字段的错误消息。或者,猫鼬错误应该返回一个path属性,该属性指向导致错误的特定字段(猜猜你要求什么)。有关更多信息,请查看 mongoose 文档mongoosejs.com/docs/validation.html -
我知道错误消息会显示失败的字段,但是我如何通过检查诸如 error_field == 'email or username' 之类的内容来返回错误消息?
标签: mongodb validation mongoose