node.js – node js/mongodb: Update document while looping object/array

I want to loop an array, and for every instance, find a document from mongodb, do some task, and increment the document’s value. But I only got the document incremented once. (That’s my problem);

const routes = [{name: 'route1'}, {name: 'route2'}];

for (let i = 0; i < 5; i++) {
 setRouteHeader(i, routes);
}


async function setRouteHeader(i, routes) {
 for (let route of routes) {
  let lastOffset = await Routes.findOne({name: route.name});
  let lo = lastOffset.offset;
  lo++
  console.log(lo)
  // Do some task
  // ...
  await Routes.updateOne({name: route.name}, {offset: lo});
 }
}

When i start the loop with offset 0 in the database, i only have :
`

1
1
1
3
3

Read more here: Source link