首页 > 解决方案 > 在通过云函数在 Firestore 中进行更改后从文档中检索对象数组

问题描述

我有一个 Firestore 文档,其中包含一个名为 items 的字段,该字段是制作每个项目的对象数组。这是结构:

- Document1
              | document_status
              | items
                     | item1
                     |   | name
                     |   | item_status
                     | item2
                     |   | name
                     |   | item_status

现在我正在使用 onUpdate() 方法收听文档更新,该方法工作正常。例如:如果 document_status 发生变化,那么我会在 change.after.data() 方法中得到变化。但是我需要通过change.after.ref获取对“items”字段的引用,以便我可以浏览每个项目并更改item_status

我只想通过 **change而不是直接访问文档。因为我使用通配符来检索文档参考**

我在这里看到了一个很接近的例子:https ://github.com/firebase/functions-samples/blob/master/limit-children/functions/index.js#L27-L39但不幸的是我无法尝试更深入并得到项目子项的参考。

这是我尝试过的:

exports.sampleFunction = functions.firestore
        .document(‘mycollection/{documentId}/subCollection/{mydocuments}’).onUpdate((change, context) => {
        const newData = change.after.data();
        const documentStatus = newData.document_status;
         const parentRef = change.after.ref.child("items");
          return parentRef.once('value').then((snapshot) => {
            snapshot.forEach((item) => {
              updates[item.item_status] = "some_value"
            });
            return parentRef.update(updates);
          });
        }
        return;
    });

我也尝试过使用:

change.after.ref.parent.child("items");

和不同的组合。但我收到如下错误:

TypeError: change.after.ref.child is not a function
    at exports.sample_function.functions.firestore.document.onUpdate (/user_code/index.js:31:46)
    at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
    at next (native)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
    at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
    at /var/tmp/worker/worker.js:710:26
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

请建议我如何浏览所有项目并将所有item_status更新为 some_value

标签: node.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


推荐阅读