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;
}
}
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
.
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.
© 2024 OneMinuteCode. All rights reserved.