node.jsmongodbmongoose

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

Solution

  • You are not awaiting in the initial for loop so setRouteHeader is called multiple times simultaneously. This causes the find and update operations to overlap causing what you have observed here. To fix it wrap the for loop in an asynchronous function and add await before calling setRouteHeader then call this asynchronous function