1

I'm trying to update multiple documents with a loop, and decrement the "weeks" field in each Phase by one (1). Seems simple enough, and here is the code:

//Go through masterPhaseArray and decrement a week for each phase
for(let i=0; i<res.locals.masterPhaseArray.length; i++){
    
    console.log("doubles? "+res.locals.masterPhaseArray[i]._id)
    
    await Phases.findByIdAndUpdate({_id: res.locals.masterPhaseArray[i]._id}, {$inc: {weeks: -1}}, (err, doc) => {
         console.log("finished")
    })
}

The issue is, it is actually decrementing by 2.

When I tried reversing it to increment +1, it started incrementing +2.

I assumed I must be double-looping somehow, so I added a console.log, and here is the result:

[0] Connection established to mongodb://localhost:12345/teamy
[0] doubles? 5e44cc20c74f8a444851d2c3
[0] finished

As you can see the _id only passed once, and yet the result in the database shows:

Before  { weeks: 6 }
After   { weeks: 4 }

I've revisited the MongoDB docs for $inc, and it is very straight forward. I've googled this issue and also can't find anything like this. Appreciate any new perspectives.

Izzi
  • 2,184
  • 1
  • 16
  • 26
  • After I posted this, I tried removing the "async" and "await", and it fixed the issue. But I don't know why? – Izzi Aug 27 '20 at 08:07

1 Answers1

0

Check masterPhaseArray objects (count and order) in cycle. It seems like somehow you add duplicate to your array in time when Phases.findByIdAndUpdate executed.

Cleaning from async block process and your changes of Array executed after cycle is done.

  • I tested this multiple ways, and the Array only contains (1) object. But it seems like the async/await is somehow "holding" the query, and allowing double increments? – Izzi Aug 27 '20 at 08:55
  • @IsraelPeck async-await wait until your request is done. Hmmm... Try to create copy of your array and use 'for of'. `const array = [ ...res.locals.masterPhaseArray ]; for(const item of array){ ...your logic }` – LonelySpirit Aug 27 '20 at 09:04