【问题标题】:Updating Query in Firestore在 Firestore 中更新查询
【发布时间】:2018-07-26 15:49:55
【问题描述】:

我是 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!"); }) 

【问题讨论】:

  • 这是我想要做的: 'Scott' },{merge:true}) .then(function() { console.log("文档更新成功!"); })

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-09-06
    • 1970-01-01
    • 2019-02-19
    • 2018-09-16
    • 2021-10-22
    • 2020-10-31
    • 2021-02-06
    • 1970-01-01
    • 2019-04-22
    相关资源
    最近更新 更多