首页 > 解决方案 > 在 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!"); }) 

标签: javascriptgoogle-cloud-firestorefirebase-admin

解决方案


Employee只是 Firestore 文档中嵌入的数据结构,因此您无法通过引用直接解决它。就 Firestore 而言,Employee它只是Department文档上的一个属性Name

在我提出解决方案之前,让我指出两点:

  1. 如果使用update,则不需要{merge: true}. 如果文档已经存在,您可以使用{merge: true}withset来获得类似更新的行为。
  2. 我不会使用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)。


推荐阅读