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

Time:11-19

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

CodePudding user response:

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

CodePudding user response:

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

  • Related