Node.js catches only MongoDB unique constraint errors

Asked 1 years ago, Updated 1 years ago, 88 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.

try{
    wait db.collection("hoge")
            .insert(foo);
}catch(e){
    if (/*e is unique error */) {
        // Processing
    } else {
        through;
    }
}

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.
https://github.com/mongodb/mongo/blob/8b3694d704d4c472adba87e8fb0827372324c215/src/mongo/base/error_codes.err#L237

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.
https://docs.mongodb.com/manual/core/index-unique/

The specific error that occurs depends on the driver.


2022-09-30 11:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.