简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM