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()
添加回答
舉報