我有一个包含对象数组的字段achivment
。我需要更新一个对象中的字段currentPoints
,我将通过数组中的字段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
字段的对象。
1条答案
按热度按时间nqwrtyyt1#
您应该使用以下内容进行更新