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.