1

Straight Forwardly:

I am clicking the button two times from the same machine(user) or from the different machine(user) within the span of 1 seconds. It's creating two documents (duplicates).

In short may be how to handle multiple API calls parallelly or concurrently.

What I suspect:

  1. Nodejs collects the API call -> db.find(name) -> Not Found-> Creating New document (Its running)

Before the above document creation done. Nodejs started executing the next API call.

  1. Nodejs collects the API call -> db.find(name) -> Not Found -> Creating New document.

Example Code: Here two account with same name is created.

 const userPresent = await User.findOne({ phoneNumber: data.phoneNumber, }); if (userPresent) { throw new CustomError("OIC_ERROR_00027", "User already present"); } // new account created const newAccount = await new Account({ name: data.name, }).save(); 

2 Answers 2

1

You may try to create a unique index for your product name. This will cause your product name to not have any duplicates.

db.collection.createIndex( {"name":1} , { unique: true } ) 
Sign up to request clarification or add additional context in comments.

11 Comments

But, I don't want the same name to repeat
yea it will not have any duplicates ... have you even try it out
Please check the edited code in the question can your solution secure the above problem ? When more or 1000 calls happens at the same time. I am just super curious
And to my knowledge it just acts as a primary key ?
By creating a unique index MongoDB prevent any same {name:"name"} document to be created, an error will be returned on your subsequent .save() command with {name:"name"}. So only one instance of said document can be found in your document
|
0

The problem was I given autoindex: false in option while connecting to MongoDB. So The DB was not taking indexing commands in mongoose schema. I removed the autoindex: false and followed @koodies guidance. Thanks now working !

But Not working when I try to create connection and use it like db.model("modelName")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.