javascript - 更新 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'
}],
});
解决方案
您可以使用$inc运算符并运行更新操作,例如:
UserWeaponSchema.update({ weapon: weaponId, user: userId }, { '$inc': { 'kills': newAmmountOfKills } })
推荐阅读
- laravel - VUE.JS 模板未显示
- python - 在列子集和索引上合并两个 pandas DataFrame
- python - 如何让屏幕忽略某些图像的背景颜色?
- python - 无法对提供给加载的朴素贝叶斯模型的用户输入值进行编码?
- c++ - 尝试使用 OpenGL 制作 Endless Runner C++
- c# - Razor Tag Helper - 绑定到集合
- c++11 - 朋友别名模板不能用 clang 编译
- lua - 如何使用 lua 设置 cmusphinx?
- angular - 将应用程序发布到 IIS 后访问服务时出现 400 错误请求
- javascript - 使用 react-router 自定义动态路由