2 回答

TA贡献1895条经验 获得超7个赞
发生的情况是您使用前面的点来计算下一个分数,而不是使用 mongoDB$inc运算符
选项 1 使用回调,丑陋且根本不可读
Tips.find({})
.exec(function(err, gameTips) {
if(err) {
console.error(err);
return;
}
gameTips.forEach(tip => {
User.findOneAndUpdate(
{ username: tip.username },
{ $inc: { points: tip.points }}
).exec(function(err, user) {
if(err) {
console.error(err);
return;
}
console.log("Points were increased");
})
})
})
选项 2 使用Promises,更具可读性Promise.all()
Tips.find({})
.then(gameTips => Promise.all(gameTips.map(tip => User.updateOne(
{ username: tip.username},
{ $inc: { points: tip.points } }
)))
.then(() => {
console.log("Points were increased");
})
.catch(console.error)
选项 3 使用async/await,我最喜欢的,简单易读
async function run() {
try {
const gameTips = await Tips.find({});
await Promise.all(gameTips.map(tip => User.updateOne(
{ username: tip.username},
{ $inc: { points: tip.points } }
)));
console.log("Points were increased");
} catch (err) {
console.error(err);
}
}

TA贡献1786条经验 获得超13个赞
您不能像在 中使用异步代码那样使用它forEach,它不会产生所需的结果。您可以使用for ofwithasync await来获得更清晰的代码:
async function updateTips() {
try {
const tips = await Tips.find({condition: 'condition'})
if (tips.length) { // check for empty result
for (const tip of tips) {
let user = await User.findOne({ username: tip.username })
if (user) {
user.points = user.points + 1
await user.save()
console.log('Points were increased')
}
}
}
} catch (err) {
// handle errors here
}
}
updateTips()
添加回答
举报