javascript - 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上,我只能找到更新嵌套对象而不是嵌套数组对象。
解决方案
确实不可能使用点符号或其他方式更新数组中的单个元素。要更新数组,您需要:
- 阅读文档
- 从中获取数组的当前值
- 确定新的数组内容
- 将整个更新后的数组写回数据库。
唯一的替代数组操作是array-union
and array-remove
,它在数组中添加和删除唯一元素 - 本质上将其视为数学集合。但是由于您要更新现有元素,因此这些操作在这里没有用。
另见:
推荐阅读
- jquery - 如何使用 DataTables 分页插件对表格进行分页
- ios - Swift 4 - Alamofire - 如何根据请求禁用缓存
- python - 将负值更改为 0,而不更改其他列
- python - python 语法问题 - 为什么这段代码没有生成预期的输出?
- android - Java 和 Vuforia Android SDK 的区别
- visual-studio-code - Electron 应用程序大小对于 linux 是 450 mb,对于 windows 是 238 mb,如何相对于 Visual Studio 代码减小它
- json - 飞镖中的Json解析(颤振)
- firebase - 在 onTrigger 函数上使用可调用函数
- google-maps - 如何在 Flutter 中设置 Google Map 主题?
- google-cloud-platform - 谷歌云函数抛出 404 错误