skip to Main Content

I use MongoDB to store user data. The user id goes incrementally, such as 1, 2, 3, 4 etc when new user register.

I have the following code to generate the user id. "users" is the name of the collection where I store the user data.

// generate new user id
let uid;
const collections = await db.listCollections().toArray();
const collectionNames = collections.map(collection => collection.name);

if(collectionNames.indexOf("users") == -1){
    uid = 1;
}
else{
    const newest_user = await db.collection("users").find({}).sort({"_id":-1}).limit(1).toArray();
    uid = newest_user[0]["_id"] + 1;
}
user._id = uid;


// add and save user
db.collection("users").insertOne(user).catch((error)=>{
    throw error;
});

One concern I have now is that when two users make a request to register at the same time, they will get same maximum user id, and create the same new user id. One way to prevent it is using a locked thread. But, I think Node.js and Next.js doesn’t support multi-thread.
What are some alternatives I have to solve this problem?

In addition, _id will be the field for uid. Will it make a difference since _id can’t be duplicated.

2

Answers


  1. Chosen as BEST ANSWER

    One idea I have is using a transaction which can solve the concurrency issue. Transactions obey the rule of ACID. The writes to the database from the concurrent requests will run in isolation.


  2. Why not have the database generate the auto-incrementing ID? https://www.mongodb.com/basics/mongodb-auto-increment

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search