【问题标题】:Cloud firestore: Update field values in nested array object with dot notationCloud firestore:使用点表示法更新嵌套数组对象中的字段值
【发布时间】:2021-02-02 07:42:37
【问题描述】:

请帮我解决这个问题,我想使用点符号更新字段,使用 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 上,我只能找到更新嵌套对象,但找不到嵌套数组对象。

【问题讨论】:

    标签: javascript firebase google-cloud-platform google-cloud-firestore


    【解决方案1】:

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

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

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

    另见:

    【讨论】:

    • 非常感谢您的明确回复和有用的相关链接@Frank 我正在失去理智,因为我认为缺少一些东西。但显然,更新数组中的单个元素是一件很麻烦的事情。
    猜你喜欢
    • 2021-04-14
    • 2018-04-27
    • 2019-02-13
    • 2019-05-28
    • 2018-08-15
    • 2020-05-08
    • 2023-01-27
    • 2021-12-15
    相关资源
    最近更新 更多