【发布时间】:2020-12-16 01:53:03
【问题描述】:
我正在尝试使用循环更新多个文档,并将每个阶段中的“周”字段减一 (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
如您所见,_id 只传递了一次,但数据库中的结果显示:
Before { weeks: 6 }
After { weeks: 4 }
我重新访问了 $inc 的 MongoDB 文档,它非常简单。我用谷歌搜索了这个问题,也找不到类似的东西。欣赏任何新观点。
【问题讨论】:
-
发布后,我尝试删除“async”和“await”,它解决了问题。但我不知道为什么?
标签: javascript mongodb decrement