简体   繁体   English

在集合中插入多个条目

[英]Inserting multiple entries in collection

I am attempting to create barcodes that increment by 1 for an entered quantity and add each of them to a MongoDB collection. 我正在尝试为输入的数量创建递增1的条形码,并将每个条形码添加到MongoDB集合中。

I use db.controlNumber.insert({controlNumber}) to do this, and I also use console.log(controlNumber) to see my result. 我使用db.controlNumber.insert({controlNumber})来做到这一点,并且我也使用console.log(controlNumber)来查看我的结果。 However, in the database, the incremented number will go to the max and enter that many times, where the console.log shows it increment. 但是,在数据库中,递增的数字将达到最大值并输入多次,在console.log中显示递增的数字。

while (i < count) {
  i++;

  controlNumber.controlNumber = controlVar[0] + "-" + controlVar[1] + "-" + 
  controlVar[2] + "-" + controlVar[3] + "-000" + i;
  db.controlNumber.insert(controlNumber);
  console.log(controlNumber);     
}

I expect my mongoDB collection to have control number (for example if user wants 5 control numbers) 我希望我的mongoDB集合具有控制号(例如,如果用户要5个控制号)

a-b-c-d-001  
a-b-c-d-002  
...  
a-b-c-d-005

Instead, it makes 5 entries of 相反,它使5个条目

a-b-c-d-005

You're mutating controlNumber.controlNumber . 您正在变异controlNumber.controlNumber Instead, create a new object to insert: 而是创建一个新对象以插入:

const toInsert = Object.assign({}, controlNumber, { controlNumber: i });
db.controlNumber.insert(toInsert)

It'd likely also be worth either using async/await or promises to handle asynchronous calls. 使用async/await或promises处理异步调用也很值得。 If you do await db.controlNumber.insert(controlNumber) you wouldn't have run into any problems because it would have waited for the document to be fully inserted before moving on to the next one. 如果您确实await db.controlNumber.insert(controlNumber)那么您将不会遇到任何问题,因为在继续进行下一个操作之前,它会等待文档完全插入。

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

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