Node.js catches only MongoDB unique constraint errors

Asked 2 months ago, Updated 2 months ago, 5 views

I am using TypeScript.
I would like to determine the following unique constraint error. What should I do?
Looking at the type definition of the MongoError object, it seems that there are only the message, stack, and name fields.

    wait db.collection("hoge")
    if (/*e is unique error */) {
        // Processing
    } else {

javascript node.js typescript mongodb

2022-09-30 11:42

2 Answers

As for determining whether MongoDB has encountered a unique constraint, I have done so by checking the returned error code.

If it's a unique limitation, I think it's better to decide whether it's 11000.

I think I used Mongoose when I used it before, but I think I got it with err.code.

2022-09-30 11:42

Unique Index can be added to create unique constraints.

The specific error that occurs depends on the driver.

2022-09-30 11:42

If you have any answers or tips

© 2022 OneMinuteCode. All rights reserved.