Cloud firestore:使用点表示法更新嵌套数组对象中的字段值

Sab*_*tiG 6 javascript firebase google-cloud-platform google-cloud-firestore

请帮我解决这个问题,我想使用点表示法、使用 set() 来更新字段,但每次我运行以下实现时。我将字段添加到 firestore 中,例如,studentInfo.0.course.0.courseId而不是更新已经存在的字段。

Json 样本位于 firestore 中

    "schoolId": "school123",
    "studentInfo": [
        {
            "studentId": "studentI23",
            "regDate": "2020-04-18",
            "course": [
                {
                    "courseId": "cs123",
                    "regDate": "2020-05-28",
                    "status": "COMPLETED"
                }
            ]
        
        }
    ],
    "registered":"yes"
}
Run Code Online (Sandbox Code Playgroud)

代码逻辑

const query = firestore.collection('users').where('registered', '==', 'yes')
const students = await query.get()
 students.forEach(student => {
    firestore.doc(student.ref.path).set({
        'studentInfo.0.studentId': '345','studentInfo.0.course.0.courseId': '555'
      }, { merge: true })
 }) 
Run Code Online (Sandbox Code Playgroud)

在文档https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects上,我只能找到更新嵌套对象,但不能找到嵌套数组对象。

Fra*_*len 8

确实不可能使用点表示法或其他方式更新数组中的单个元素。要更新数组,您需要:

  1. 阅读文档
  2. 从中获取数组的当前值
  3. 确定新的数组内容
  4. 将整个更新后的数组写回数据库。

唯一的替代数组操作是array-unionand array-remove,它们向数组添加或从数组中删除唯一元素 - 本质上将其视为一个数学集合。但由于您要更新现有元素,因此这些操作在这里没有用。

另请参阅: