URL Shortener Microservice: multiple requests

Hi everyone! I’m doing this project using Express, mongodb(MongoDB Atlas) & mongoose and this is what my app will do when a request arrives: it will query if this url existed. If not then insert new document, else get the existed one and return to user.

Here’s a user story: When 2 requests (A & B) with the same url arrives at the same time and the url isn’t in database yet, I think this is what will happen because find and add is asynchronous:
my app finds the url for A (not existed)
-> my app finds the url for B (not existed)
-> add the url to database (request A)
-> add the url to database (request B) => but the url is already existed so this is wrong.

I wonder if i understand it right? If yes, how can i solve this? If not then how will it works in this case?
Thank you!

Hi,
If you use autoincrement id, the second query will send back an error because cannot to store two documents with a same _id…
I got this error while I developed my code… when I clicked to the refresh button very quickly while the mongoDbAtlas was in “sleep mode”.
If you use the random id by created mondoDbAtlas… I don’t know what will happen… Problably the same url will be store double times. But this is not a problem at all because the findOne method returns the first occurrence in the selection.
But if you want, after the response sending, you can write more some database handle code…
Because your code still can run, only you cannot to send another response… Example you can query another find() with the same url and if the find method give back more than one documents… just simple delete the unwanted data…