title: How to Handle Multiple user request at the same time in node js
body: <p>I have created a route <code>'/api/checkUsername'</code>. Which action is to check if there is any user exists with the <code>same username</code>. If not Save the new <code>UserName</code> in users collection and update the users count in another collection. </p>
  
  <p>For the route, I have a function as </p>
  
  <pre><code>async function(username) {
     IsUserNameExists = await db.findOne({ 'username': username });
  
     if(IsUserNameExists) {
        res.send({ message: 'username already exists');  
    }else{
        await user.save() //to save user in DB
        await updateUserCount() //update user count in collection 2 
        res.send({ message: 'user saved successfully' });
    } 
  
  }
  </code></pre>
  
  <p>This works fine with all use cases. But a case like if 2 users [<code>'user1', 'user2'</code>] user check for the same username <code>eg: Tony_Stark</code> at the same second or with few milli-second difference. </p>
  
  <p><code>eg</code> user1 and user2 hits <code>/api/checkUsername</code> at the same time or with millisecond difference. user 1 finds that username <code>Tony_Stark</code> is available and saving his username, but in between saving the user name the user2 also looks for the username <code>Tony_Stark</code> which has not been saved by user1, So it makes that username available for user2 also. Which creates a duplicate entry in my collection. How do I avoid this?</p>