【问题标题】:Firebase Cloudfirestore update elements in a collectionsFirebase Cloud Firestore 更新集合中的元素
【发布时间】:2020-09-27 16:51:57
【问题描述】:

我正在使用带有 nodejs 和 cloudfirestore 的 firebase 函数来构建 API,现在我遇到了一个问题,我有一个集合,集合中有一个对象数组。

我的目标是只更新特定元素而不读取整个对象,然后再次推送。

这就是我的“订单收藏”的样子:

"someRestaurantId":[{id:1,desc:"test",val:3000},{id:2,desc:"test",val:4000},{id:4,desc:"test",val:5000}]

我的目标仅更新 id 2。

这是我一直在尝试的:

获取基于的完整列表

const document = db.collection('orders').doc(req.params.restId);

迭代并找到正确的元素,对其进行修改并再次更新。

await document.update(fullobject)

问题是我需要一些更容易处理的东西,因为该数组中可能有数千个元素。

【问题讨论】:

    标签: node.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    查看所描述的问题,我认为您应该为此使用subcollection(有时称为嵌套集合)。但是从描述中很难判断你现在拥有什么。

    Firestore 集合结构总是这样:

    collection -> document -> fields and nestedCollections

    nestedCollection 具有相同的结构,因此您可以将整个结构嵌套多少次,但始终集合只包含文档,每个文档只包含字段和集合。

    在呈现的集合中,描述数组是直接在集合中还是直接在文档中,这两者都不可能。

    无论如何,我的想法是按照以下方式构建它:

    • 包含各种 restID 文档的集合订单
    • 每个文档(例如“someRestaurantId”)都包含名称为 ex 的子集合。 “休息订单”
    • 在子集合中将添加 ID 为 (1,2,3 等) 的文档
    • 子集合中的每个文档都有descval字段
    Collection Orders:
        Document RestID_1:
             Subcolection RestOrders:
                  Document 1: {val: 3000, desc: test}
                  Document 2: {val: 3000, desc: test}
                  ...
        Document RestID_2:
             Subcolection RestOrders:
                  Document 1: {val: 3000, desc: test}
                  Document 2: {val: 3000, desc: test}
                  ...
    

    现在要更新“RestID_1”的值,您可以使用命令“id 2”:

    db.collection('Orders')
     .doc('RestID_1')
     .collection('RestOrders')
     .doc('2')
     .update( {val: 4000} )
    

    在上述解决方案中,您避免读取和更新大数组。您只能更新嵌套子集合中的一个文档的一个字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 2019-02-14
      • 2020-05-20
      • 2019-03-28
      • 2018-04-30
      • 1970-01-01
      • 2018-11-07
      相关资源
      最近更新 更多