如何使用猫鼬多次正确触发架构方法



我正在尝试两次触发用户方法,但猫鼬抱怨在paralell中保存:

ParallelSaveError: Can't save() the same doc multiple times in parallel

awaitPromises数组内部有两种相同的方法,我认为使用await Promise.all()会很顺利。遗憾的是,不可能事先将值相加以仅运行一次该方法。

长话短说:如何在不遇到.save()问题的情况下两次触发相同的用户方法?

// User.js (Model)
const mongoose = require("mongoose");
const { Schema } = mongoose;
const userSchema = new Schema({
account: {
username: String,
discordId: String
},
stats: {
attack: 50
},
hero: {
rank: 0,
currentHealth: 100
}
userSchema.methods.loseHp = function(damage) {
this.hero.currentHealth -= damage
if (this.hero.currentHealth <= 0) {
this.hero.currentHealth = 1
}
return this.save();
};
module.exports = mongoose.model("User", userSchema);
// gameLogic.js
const calculateResult = async (player, enemy)=>{
const awaitPromises = [];
for (let i = 0; i < enemy.allowedAttacks; i += 1) { // max 3 iterations
awaitPromises.push(player.loseHp(Math.random()*enemy.stats.attack))
}

try {
await Promise.all(awaitPromises)
} catch(error){
console.log('error: ', error)
}
}
  1. 承诺立即开始执行,Promise.all所做的只是返回一个承诺,当所有传递的承诺都实现时,该承诺就会实现(但那时它们可能已经实现!如果 Mongoose 不喜欢飞行中同一模型的两个承诺,您可能需要在循环中逐个执行它们:
await player.loseHp(Math.random()*enemy.stats.attack);
  1. 为什么多次调用loseHp?难道你不能把伤害加起来,最后给loseHp打电话一次吗?

最新更新