首页 > 解决方案 > Cloud firestore:使用点表示法更新嵌套数组对象中的字段值

问题描述

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

位于 Firestore 中的 Json 样本

    "schoolId": "school123",
    "studentInfo": [
        {
            "studentId": "studentI23",
            "regDate": "2020-04-18",
            "course": [
                {
                    "courseId": "cs123",
                    "regDate": "2020-05-28",
                    "status": "COMPLETED"
                }
            ]
        
        }
    ],
    "registered":"yes"
}

代码逻辑

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 })
 }) 

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

标签: javascriptfirebasegoogle-cloud-platformgoogle-cloud-firestore

解决方案


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

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

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

另见:


推荐阅读