Cloud Firestore:使用点表示法更新嵌套数组对象中的字段值 [英] Cloud firestore: Update field values in nested array object with dot notation

查看:35
本文介绍了Cloud Firestore:使用点表示法更新嵌套数组对象中的字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我解决这个问题,我想使用点表示法(使用set()来更新字段),但是每次使用以下实现运行时,我都会对其进行更新.我将字段添加为Firestore作为例如 studentInfo.0.course.0.courseId ,而不是更新现有的字段.

Please help me solve this, I would like to update the fields using dot notation, using set() but each time I run with the below implementation. I have the fields added to firestore as e.g studentInfo.0.course.0.courseId instead of updating the already existing ones.

Json放在壁炉中的样本

Json sample as it sits in firestore

    "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 我只能找到更新的嵌套对象,而不能找到嵌套的数组对象.

On the docs https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects I can only find updating nested objects but not nested array objects.

推荐答案

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

It is indeed not possible to update a single element in an array using dot notation, or otherwise. To update an array you'll need to:

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

唯一可选的数组操作是 array-union array-remove ,它们在数组中添加唯一元素或从数组中删除唯一元素-本质上将其视为数学集合.但是,由于您要更新现有元素,因此此处没有这些操作.

The only alternative array operations are array-union and array-remove, which add and remove unique elements to/from the array - essentially treating it as a mathematical set. But since you are looking to update an existing element, these operations are of no use here.

另请参阅:

这篇关于Cloud Firestore:使用点表示法更新嵌套数组对象中的字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆