gpt4 book ai didi

mongoDB DuplicateKey error is undefined when trying to insert a duplicated email(尝试插入重复的电子邮件时,MongoDB DuplicateKey错误未定义)

转载 作者:bug小助手 更新时间:2023-10-25 14:33:19 31 4
gpt4 key购买 nike



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:

对于重复的用户名:


enter image description here


for duplicated email :

对于重复的电子邮件:


enter image description here


更多回答
优秀答案推荐

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.

很好的选择。祝你的项目好运。

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com