简体   繁体   中英

insert document in bulk using for loop mongoose

Why this won't insert 20 document for me?

for (let i = 0; i <= 20; i++) {
  const [updated] = await Promise.all([
    Job.findOneAndUpdate(
      { _id: id },
      {
        $set: {
          status: 'something'
        }
      },
      { upsert: true, new: true }
    ),
    User.findOneAndUpdate(
      { _id: userId },
      {
        $set: { assigned: true }
      },
      { upsert: true, new: true }
    )
  ])
}

or I should use reduce and Promise resolve? Above query worked just that it doesn't insert 20 documents, it inserted one document.

If you have array of id then you can use bulkWrite

const id = ['844646464', '45646546546', '45646546546']

Model.bulkWrite(
  req.body.idArray((id) => {
    return ({
      updateOne: {
        filter: { _id: id },
        update: { $set: { status: 'something' } },
        upsert: true
      }
    })
  })
})

It will create a request something like this

bulkWrite([
   { updateOne: { filter: { _id: id }, update: { $set: { status: 'something' } } },
   { updateOne: { filter: { _id: id }, update: { $set: { status: 'something' } } },
   { updateOne: { filter: { _id: id }, update: { $set: { status: 'something' } } } 
])

Which efficiently performs all updates in a single request to the server with a single response.

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