1

I have 2 unique keys in my userSchema:

email: {
        type: String,
        required: true,
        unique: true
    },
username: {
        type: String,
        required: true,
        unique: true
    }

You can't add neither username nor email which already exist in the database. How can I tell user which one exactly already exists in the database, because there is only one error code?

if (err.code == 11000)
    return res.status(422).send(['Duplicate email adrress found.']);

1 Answer 1

1

For these two uniques indexes on email & username, if you can get index names using :

db.collectionName.getIndexSpecs()

Then while on inserts if you get duplicate key error :

WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 11000,
      "errmsg" : "E11000 duplicate key error index: test.collection.$a.b_1 dup key: { : null }"
   }
})

In your code you can do :

if (err.code == 11000) {
  if (err.msg.includes("email_1")) { // assuming name is `email_1` & also you can trim msg to get failing input value.
    return res.status(422).send(["Duplicate email address found."]);
  } else {
    return res.status(422).send(["Duplicate username found."]);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, and just one more thing; how can I do that on front in angular, because I check there only this: if (err.status === 422)
@Dragana : Nope this code is for API, your API has to have this check & send appropriate message to front-end with code 422 or 409 or some-other, it's doesn't matter whether node.js or angular/react where ever you're doing DB call you need to check this & pass it on to further layers(if your DB call is in front-end angular then you can do this there if DB call is not in angular then your API has to source it unless with API sourcing proper msg, you can't differentiate in Angular)..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.