mongodb - 更改对象数组中对象中的字段
问题描述
我有一个achivment
包含对象数组的字段。我需要更新currenPoints
一个对象中的字段,我将通过name
数组中的字段找到该对象。
mongoose的代码模型:
const achive = new Schema(
{
achiveId: ObjectId,
name: { type: String, required: true },
finishedPoints: { type: Number, required: true },
currentPoints: {
type: Number,
default: 0,
set: function (v) {
if (v >= this.finishedPoints) this.isFinished = true;
return v;
}
},
isFinished: { type: Boolean, default: false }
},
{ _id: false }
);
const achivesSchema = new Schema({
userId: ObjectId,
achivement: [achive]
});
代码查询:
export async function progressAchive(req, res) {
const value = 3;
try {
const test = await Achives.updateOne(
{
userId: req.user._id,
achivement: { $elemMatch: { name: req.params.nameAchive } }
},
{ $set: { achivement: { currentPoints: value } } },
{ new: true }
);
res.json(test);
} catch (e) {
console.log(e);
}
}
它不是更新,而是从数组中删除所有对象,并将它们保留为一个包含该currentPoint
字段的对象。我怎样才能像我想要的那样更新它?
解决方案
您应该使用以下内容进行更新
const test = await Achives.updateOne(
{
userId: req.user._id,
},
{
$set:{"achivement.$[el].currentPoints": value}
},
{
arrayFilters:[{
"el.name": req.params.nameAchive
}],
new: true
}
);
推荐阅读
- python - 'beeline' 未被识别为内部或外部命令
- sql - 使用 JOIN 中的两个 OR 语句保持数据质量并加快查询速度
- reactjs - 在反应中迭代Json对象
- javascript - 删除过滤器方法React / JS中的多个项目
- php - 使用 Laravel Socialite 注册和登录 Facebook
- node.js - MongoDb 获取数据时出现聚合错误
- python-3.x - Python 3,BeautifulSoup 4:find_all 具有特定属性的多个标签
- python-3.x - Tkinter 条目在每次运行时都给我()而不是在 GUI 中输入的值
- c# - 如何使 RichTextBox 水平自动滚动
- python - 将(新)pandas DF 写入具有不同列数的 sql