问题描述
我试图循环更新多个文档,并将每个阶段的“周”字段减一(1)。看起来很简单,这是代码:
//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")
})
}
问题是,实际上是递减2。
当我尝试将其反转以增加+1时,它开始以+2递增。
我认为我必须以某种方式进行双循环,所以我添加了console.log,结果如下:
[0] Connection established to mongodb://localhost:12345/teamy
[0] doubles? 5e44cc20c74f8a444851d2c3
[0] finished
Before { weeks: 6 }
After { weeks: 4 }
我以$ inc的价格重新访问了MongoDB文档,这非常简单。我已经用Google搜索这个问题,也找不到这样的东西。欣赏任何新观点。
解决方法
循环检查masterPhaseArray
个对象(计数和顺序)。
似乎以某种方式在执行Phases.findByIdAndUpdate
时及时将重复项添加到数组中。
从异步块处理中清除数据,并在循环后执行对Array
的更改。