Mongodb key duplication error. How to get an error field from an error object as an object?

When I try to enter a new document in mongo with a value in a field that already exists in another document, I get this when I repeat the error object:

for(var att in err){ console.log(att+": "+err[att]); } 

name: MongoError err: E11000 duplicate key error index: draw.users. $ email_1 dup key: {: " spam@online.no "} code: 11000 n: 0 ok: 1

So this tells me that I want to know the problem in the email field. But can I get the offending field as a key / value, and not just a string?

+6
source share
4 answers

I use regex. Like this

 if(err){ field = err.err.match(/\$(.*?)_/)[1] } 

These are absolutely hacks, but it works for me.

+3
source

If it collides, then creating find () for this query will return the collision objects and you will be from there.

0
source

The error message does not give you the information you are looking for:

name: MongoError err: E11000 duplicate key error index: draw.users. $ email_1 dup key: {: " spam@online.no "} code: 11000 n: 0 ok: 1

But it gives you enough to get it.

You need to get the index causing the problem: "email_1" (use regex)

Then you need to ask db about this index:

draw.users.getIndexKey ("EMAIL_1")

0
source

Using split in the error message returned me working this way

 var x= err.errmsg.split("index:")[1].split("dup key")[0].split("_")[0]; 
0
source

Source: https://habr.com/ru/post/949014/


All Articles