[英]How can i simultenously update the same field in a MongoDB Record?
I'm trying to update a particular field in a user row, and I'm using a forEach loop to do this, but it's only the last loop to run that gets updated.我正在尝试更新用户行中的特定字段,并且我正在使用 forEach 循环来执行此操作,但它只是运行的最后一个循环才会更新。 here's how my code looks:这是我的代码的外观:
const UserSchema = require('../models/UserSchema');
const updates = [100, 200];
const userID = req.user.id;
updates.forEach(update => {
UserSchema.findByID(userID).then(user => {
user.balance += update;
user.save.then(user => console.log('user balance updated'));
})
})
After running this code, the user's balance should be '300', but instead it's '200'..it's like the last one to run overwrites the first one because they're running at very close intervals, i can;t just wrap my head around this...please what's the solution?运行此代码后,用户的余额应该是“300”,但它是“200”......就像最后一个运行覆盖第一个,因为它们以非常接近的间隔运行,我不能只包装我的解决这个问题...请问有什么解决方案?
You are dealing with an async loop here, but the code doesn't wait for the promises to complete before moving onto the next.您在这里处理的是异步循环,但代码不会等待承诺完成,然后再进入下一个。
It's much easier using an async
function.使用async
function 会容易得多。
async function updateBalances(userID, updates){
for (const update of updates) {
const user = await UserSchema.findByID(userID)
user.balance += update
await user.save()
}
console.log('user balances updated')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.