H
H
HitGirl2021-10-04 19:58:35
MongoDB
HitGirl, 2021-10-04 19:58:35

How to correctly add an entry to the collection so that there is no duplicate key error?

Hello!
There is the following code, which checks if there is another user with the same login before registering a user:

const candidate = await UserModel.findOne({login})
        if (candidate) {
            throw ApiError.BadRequest(`Пользователь с логином ${login} уже существует`)
        }
const user:UserDocument = await UserModel.create({login, email, password: hashPassword, activationLink});

However, checking for a duplicate and creating a new user does not happen immediately. In theory, there may be a race of users during registration.
Artificial code snippet showing the problem:
const candidate = await UserModel.findOne({login})
let user:UserDocument;
        if (password==='start')
            setTimeout(async ()=> {user = await UserModel.create({login, email, password: hashPassword, activationLink})}, 20000)
        else
            user = await UserModel.create({login, email, password: hashPassword, activationLink})

In this example, users are registered at about the same time: {login: "root", email: "[email protected]", password: "start"} and {login: "root", email: "[email protected] .ru", password: "end"}. The second user will register, and after 20 seconds, an error will be received: UnhandledPromiseRejectionWarning: MongoServerError: E11000 duplicate key error collection. Question: is it worth worrying about this (the probability of such situations is very low), and if so, how can they be avoided, or at least tracked (to send a message to the first user)?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question