首页 > 解决方案 > 更新 mongo 文档数组中的单个子文档的计数

问题描述

因此,现在的示例是针对 User 表的。我嵌入了一个 UserWeapon 文档,该文档包含用户拥有的所有武器以及他们使用该武器杀死的人数。我想编写一个查询,当给定用户 ID、武器 ID 和新杀戮时,它将相应地更新子文档。

所以像

const user = await User.findById(userId);
const userWeapon = await user.userWeapon.findById(weaponId);
userWeapon.kills = userWeapon.kills + newAmmountOfKills
user.save();

最有效的方法是什么?

架构:

const UserWeaponSchema = new Schema({
    weapon: { type: Schema.Types.ObjectId, ref: 'Weapon' },
    user: { type: Schema.Types.ObjectId, ref: 'User' },
    kills: {
        type: Number,
        required: true,
        unique: false,
    },
    deaths: {
        type: Number,
        required: true,
        unique: false
    },
    equippedSkin: {
        type: Schema.Types.ObjectId, ref: 'WeaponSkin',
        required: false,
    },
    ownedWeaponSkins: [{ type: Schema.Types.ObjectId, ref: 'WeaponSkin'}]
});

const UserSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true,
    },
    password: {
        type: String,
        required: true,
    },
    weapons: [{
        type: Schema.Types.ObjectId, ref: 'UserWeapon'
    }],
});

标签: javascriptdatabasemongodbmongoose

解决方案


您可以使用$inc运算符并运行更新操作,例如:

UserWeaponSchema.update({ weapon: weaponId, user: userId }, { '$inc': { 'kills': newAmmountOfKills } })

推荐阅读