更新猫鼬对象猫鼬的嵌套数组

时间:2020-11-11 14:00:21

标签: node.js mongodb mongoose

我正在开发一个快速js应用程序,需要更新对象的嵌套数组,问题是当我尝试更新数据时,第一个对象将更新,而其余对象则不更新。

我的计划

 const Student = new mongoose.Schema({ 
       name:{
         type: String,
       },
     behaviourScores:[{
       behaviour:{
         ref:"Behaviour",
         type:ObjectId,
         require:true
      },
     score:{
        type:Number,
        require:true
     },
    class:{
       ref:"Class",
       type:ObjectId,
       require:true
     }
    }] 
})

我的有效载荷

{
    "userId": "5fa94426c88ca6e94672185a",
    "behaviours": [
            {
                "name": "Punctuality",
                "_id": "5fa04ca5ebc90c044f7d111e",
                "hasScore": false,
                "score": 0
            },
            {
                "name": "Neatness",
                "_id": "5fa08750ebc90c044f7d111f",
                "hasScore": false,
                "score": 5
            }
        ]
}

这是代码段,解释如下:

for (const behaviour of behaviours) {
 Student.findOneAndUpdate({_id:ObjectId(userId),
"behaviourScores.behaviour":ObjectId(behaviour._id), "behaviourScores.class":ObjectId(x.class)}, {"$set":{"behaviourScores.$.score":behaviour.score}},{new:true})  
                .then(b=>{
                  //     console.log(b)
                }).catch(err=>next( new APIError("User Error",err.message)))
            }

这里的问题是它仅更新第一个对象 上一个对象

 behaviourScores: [
    {
      _id: 5fabe079584ad03360dd4ec3,
      class: 5f902efb9dafe11137c5ffb1,
      score: 20,
      behaviour: 5fa04ca5ebc90c044f7d111e
    },
    {
      _id: 5fabe079584ad03360dd4ec4,
      class: 5f902efb9dafe11137c5ffb1,
      score: 4,
      behaviour: 5fa08750ebc90c044f7d111f
    }
  ]

结果对象

behaviourScores: [
    {
      _id: 5fabe079584ad03360dd4ec3,
      class: 5f902efb9dafe11137c5ffb1,
      score: 0,
      behaviour: 5fa04ca5ebc90c044f7d111e
    },
    {
      _id: 5fabe079584ad03360dd4ec4,
      class: 5f902efb9dafe11137c5ffb1,
      score: 4,
      behaviour: 5fa08750ebc90c044f7d111f
    }
  ]

0 个答案:

没有答案