dinesh oz
dinesh oz

Reputation: 342

Nodejs - concurrent or parallel API calls creates duplicates entries in mongodb

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();

Upvotes: 1

Views: 547

Answers (2)

dinesh oz
dinesh oz

Reputation: 342

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")

Upvotes: 0

Koodies
Koodies

Reputation: 550

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 } )

Upvotes: 1

Related Questions