在不知道数组中元素索引的情况下,更新多层嵌套数组中的单个数组元素(它是一个对象)

时间:2019-10-04 09:12:26

标签: mongodb mongoose mongoose-schema

我有一个对象为'Subject',其数组对象为'categories','categories'的元素为数组对象为'subCategories'的对象,'subCategories'的元素为对象,其属性名为“名称”。我需要更新“名称”的值。

这是对象。 我需要更新数组“ subCategories”中的单个元素。

例如“ name”:“ assam”到“ name”:“ rajasthan”

{
    "success": true,
    "subjects": [
        {
            "approved": false,
            "_id": "5d95decb3ade382bb834eafc",
            "name": "Geography",
            "date": "2019-10-03T11:43:07.162Z",
            "categories": [
                {
                    "approved": false,
                    "subCategories": [
                        {
                            "approved": false,
                            "_id": "5d97008cef507d0d288160ec",
                            "name": "assam"
                        },
                        {
                            "approved": false,
                            "_id": "5d9707a2798deb2fe41bf97d",
                            "name": "meghalaya"
                        }
                    ],
                    "_id": "5d97006fef507d0d288160eb",
                    "name": "India"
                }
            ],
            "__v": 0
        }
    ]
}

我尝试了以下给出错误的代码

Subjects.findOneAndUpdate({ _id: id, categories: { $elemMatch: { _id: subjectCategoryId , subCategories : { $elemMatch: { _id: subjectSubCategoryId } } } }  }, { $set: { 'categories.$.subCategories.$.name':   subjectSubCategoryName} } ,{ new: true }, (err, newSubject) => {
        if(err)
        {
             cb({success: false, error: err})
        }
        else if(!newSubject)
        {
             cb({success:false, message: 'subject Sub category cannot be found', providedSubjectID: id, providedSubjectCategoryId : subjectCategoryId, providedSubjectSubCategoryId : subjectSubCategoryId, providedName: subjectSubCategoryName})
        }
        else
        {
            cb({success: true, message: 'subject subcategory successfully updated', subject: newSubject})
        }
    })

得到此错误作为响应

{
  "success": false,
  "error": {
      "operationTime": "6743867677204283396",
      "ok": 0,
      "errmsg": "Too many positional (i.e. '$') elements found in path 'categories.$.subCategories.$.name'",
      "code": 2,
      "codeName": "BadValue",
      "$clusterTime": {
          "clusterTime": "6743867677204283396",
          "signature": {
              "hash": "p6C3D/CI+VNR4qVatfsHZIVfqc0=",
              "keyId": "6740085413039308801"
          }
      },
      "name": "MongoError"
  }
}

0 个答案:

没有答案