mongoose 更改对象数组中对象的字段

qzwqbdag  于 2022-11-24  发布在  Go
关注(0)|答案(1)|浏览(179)

我有一个包含对象数组的字段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字段的对象。

nqwrtyyt

nqwrtyyt1#

您应该使用以下内容进行更新

const test = await Achives.updateOne(
      {
        userId: req.user._id, 
      },
    {
      $set:{"achivement.$[el].currentPoints": value}
    }, 
    { 
      arrayFilters:[{
        "el.name": req.params.nameAchive
      }],
      new: true
    }
  );

相关问题