I have created many error handlers in order to handle MongoDB errors, one of them is this which is for duplicated data :
我已经创建了许多错误处理程序来处理MongoDB错误,其中一个是用于处理重复数据的:
const dbDuplicateKeyHandler = (error) => {
console.log(error);
console.log(error.keyPattern.name);
// const message = `Duplicated field value: (${error.keyValue.name}) Please use another value .`;
return new AppError(400, `Duplicated field value: (${error.keyValue.name}) Please use another value .`);
the problem is, when I try to insert a duplicated username the error message is printed as I want it to be, but in case I'm trying with a new user name but duplicated email the error.keyValue.name
will be undefined
. The handler was working correctly in Postman when I was building the API. also I've searched for the Doc that explain mongoDB errors but couldn't find any.
I console logging the error in both cases
问题是,当我尝试插入一个重复的用户名错误消息是打印出来,因为我想它是,但在情况下,我尝试与一个新的用户名,但重复的电子邮件的error.keyValue.name将是未定义的.当我构建API时,处理程序在Postman中正常工作。我也搜索了解释mongoDB错误的文档,但找不到。我控制台记录这两种情况下的错误
console.log("THE ERROR IS ==>",error);
console.log("error.keyPattern.name IS ==> ",error.keyPattern.name);
console.log("error.keyValue.name IS ==> ",error.keyValue.name);
For duplicated username:
对于重复的用户名:
for duplicated email :
对于重复的电子邮件:
更多回答
优秀答案推荐
In the case of email you are using:
如果您使用的是电子邮件:
error.keyPattern.name
error.keyValue.name
But it should be:
但它应该是:
error.keyPattern.email
error.keyValue.email
You are getting undefined
because there is no property of keyPattern
or keyValue
with a name name
.
由于没有带名称的keyPattern或KeyValue的属性,因此未定义该属性。
For consistency instead of error.keyValue.name
or error.keyValue.email
you could just do:
为了保持一致性,而不是error.keyValue.name或error.keyValue.mail,您只需执行以下操作:
console.log("error.keyPattern IS ==> ", Object.entries(error.keyPattern)[0]);
console.log("error.keyValue IS ==> ", Object.entries(error.keyValue)[0]);
//Prints
error.keyPattern IS ==> ["name", 1]
error.keyValue IS ==> ["name", "username"]
error.keyPattern IS ==> ["email", 1]
error.keyValue IS ==> ["email", "[email protected]"]
更多回答
THANKS A LOT! I used ${Object.values(error.keyValue)[0]}
to get the value entered by the user
非常感谢!我使用${OBJECT.VALUES(error.keyValue)[0]}获取用户输入的值
Excellent option. Good luck with your project.
很好的选择。祝你的项目好运。
我是一名优秀的程序员,十分优秀!