【问题标题】:Updating count of individual sub document that's in an array of a mongo document更新 mongo 文档数组中的单个子文档的计数
【发布时间】:2019-08-02 01:31:10
【问题描述】:

因此,现在的示例是针对 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'
    }],
});

【问题讨论】:

    标签: javascript database mongodb mongoose


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 2020-12-11
      • 1970-01-01
      • 2014-04-01
      • 2021-07-20
      • 2014-01-28
      • 1970-01-01
      相关资源
      最近更新 更多