I want to do bulk update on mongodb with the following code.
async function main() {
try {
const operations:any = []
users.forEach(async user => {
const custId = decrypt(user.id)
const customer = await CustomerModel.findOne({ custId: custId })
if (customer) {
let { setting, ...objData } = customer
setting = {
...setting,
...{
description: user.description
}
}
const doc = {
updateOne: {
filter: { custId: custId },
update: { location: 'USA', ...setting }
}
}
operations.push(doc)
}
})
console.log(operations)
const res = await CustomerModel.bulkWrite(operations)
} catch (error) {
console.error(error)
}
}
main()
When I execute the code above, no document is updated. I think it’s because operations.push section was called after ‘CustomerModel.bulkWrite’ is executed. When I print some debugging lines, i noticed that ‘operations.push’ was called after ‘CustomerModel.bulkWrite(operations)’ line.
Is there any way to fix it?
2
Answers
Please use a
for of
loop to execute the code sequentially:This sounds like a classic async issue indeed. In that case, you are troubled by the
.forEach()
method, which cannot await. Instead, you could use an old schoolfor...of
loop, or.map()
your Promises and await all of them: