javascript - 在 Firestore 中更新查询
问题描述
我是 Firestore 的新手,需要一些有关 Firestore 更新的帮助。
我有以下结构并想更新“员工姓名”属性。不知道如何选择和更新。
Department:[
Name: Accounts
Employee:[
{Name :David,
Age :25},
{Name:Paul,
Age:27}
]
]
这是我想做的事情:
let depempCollectionRef = admin.firestore().collection('DepEmployee').doc('depempid')
depempCollectionRef.Department.Employee
.update({ name: 'Scott' },{merge:true})
.then(function() { console.log("Document successfully updated!"); })
解决方案
Employee
只是 Firestore 文档中嵌入的数据结构,因此您无法通过引用直接解决它。就 Firestore 而言,Employee
它只是Department
文档上的一个属性Name
。
在我提出解决方案之前,让我指出两点:
- 如果使用
update
,则不需要{merge: true}
. 如果文档已经存在,您可以使用{merge: true}
withset
来获得类似更新的行为。 - 我不会使用
Array
员工。将员工存储在他们自己的 Firestore 集合中,然后在此处列出他们的参考 ID(= 外键)可能更有意义。作为一般经验法则:尽量保持数据结构平坦。也Arrays
仅在您需要保持项目的特定顺序时使用。
A)如果您有一个单独的员工集合,则更新名称很简单:
employeeCollection.doc('101').update({name: 'Scott'})
B)如果您想在部门文档中存储员工数据,我仍然会将它们存储为带有 ID(而不是Array
)的地图,然后使用点符号访问它们:
Department:[
Name: Accounts
Employees:{
101: {
Name :David,
Age :25
},
102: {
Name:Paul,
Age:27
}
}
]
depempCollectionRef.Department
.set({ ['101.name']: 'Scott' }, {merge:true})
C)如果你真的想存储嵌入的数据Array
,我相信你必须阅读并更新整个Array
(不确定,如果有更好的解决方案):
const employeesSnap = await depempCollectionRef.Department.get()
const updatedEmployees = changeNameOfScottInArray()
depempCollectionRef.Department
.update({ 'Employees': updatedEmployees })
我没有测试这段代码,但我希望你能明白它的要点!
我建议您通过创建一个单独的Employee
集合来扁平化您的数据结构,然后仅通过您部门中的外键引用它们(解决方案 A)。
推荐阅读
- android - Android 5 上的 AppCompatButton:app:backgroundTint 有效,但 supportBackgroundTintList 无效:(
- php - 将查询从 laravel eloquent 转换为原始 sql
- python - Python Pandas - 即使跨数据帧存在相同的列,pd.merge 上的 KeyError
- angular - Bearer Token 在 Postman 上工作,但不在 localhost
- bash - 通过 echo 命令使用变量中的数据发送电子邮件
- reactjs - 使用 react-jss 添加动态样式时出现格式错误的 CSS 字符串错误
- excel - Excel 宏在 240 个字符标记处添加 HTML 粗体标签“中断”
- javascript - 在 Vue.js 中使用 JS 将组件挂载到 DOM 中
- c# - 如何解决加入问题显示相同的结果
- ajax - Ajax 提交时出现 500 内部服务器错误