简体   繁体   English

Nodejs - 并发或并行 API 调用在 mongodb 中创建重复条目

[英]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.我在 1 秒内从同一台机器(用户)或不同的机器(用户)单击按钮两次。 It's creating two documents (duplicates).它正在创建两个文档(重复)。

In short may be how to handle multiple API calls parallelly or concurrently.简而言之可能是如何并行或并发地处理多个 API 调用。

What I suspect:我怀疑的是:

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

Before the above document creation done.在上述文件创建完成之前。 Nodejs started executing the next API call. Nodejs 开始执行下一个 API 调用。

  1. Nodejs collects the API call -> db.find(name) -> Not Found -> Creating New document. Nodejs 收集 API 调用 -> 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.问题是我在连接到 MongoDB 时给了autoindex: false选项。 So The DB was not taking indexing commands in mongoose schema.所以数据库没有在猫鼬模式中使用indexing命令。 I removed the autoindex: false and followed @koodies guidance.我删除了autoindex: false并遵循了@koodies 指导。 Thanks now working !感谢现在工作!

But Not working when I try to create connection and use it like db.model("modelName")但是当我尝试创建连接并像db.model("modelName")一样使用它时db.model("modelName")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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