joe
joe

Reputation: 1723

Updating count of individual sub document that's in an array of a mongo document

So the example right now is for the User table.. I have a UserWeapon document embedded that is an array of all the weapon's a user has and how many kills they have with the weapon. I want to write a query that when given the userId, weaponId, and new kills, it'll update the sub document accordingly.

So something like

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

What would be the most efficient way to do this?

Schemas:

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'
    }],
});

Upvotes: 1

Views: 24

Answers (1)

mickl
mickl

Reputation: 49985

You can use $inc operator and run update operation, something like:

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

Upvotes: 2

Related Questions