【问题标题】:How to update a document when a document is added to a specified collection in cloud firestore?将文档添加到云 Firestore 中的指定集合时如何更新文档?
【发布时间】:2020-07-31 07:44:00
【问题描述】:

我的 firestore 中有 2 个集合(全局和本地),当我将文档添加到本地时,我需要将全局文档中的字段更新 1

下面是我的代码。我对此很陌生,所以我也可能有一些语法错误,如果你发现任何问题,请高亮显示。

const functions = require("firebase-functions");
const admin = require("firebase-admin");

exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send("Hello world");
}); // For testing, even this is not being deployed

exports.updateGlobal = functions.firestore
  .document("/local/{id}")
  .onCreate((snapshot, context) => {
    console.log(snapshot.data());
    return admin
      .firebase()
      .doc("global/{id}")
      .update({
        total: admin.firestore.FieldValue.increment(1),
     });
  });

终端显示“加载用户代码时功能失败” 在此之前,它显示了“管理员未定义”或“无法访问未定义的 firestore”之类的内容,我现在无法复制。

这是通过 firebase npm 模块正常运行的 react 应用程序的一部分 有关该问题所需的任何其他信息,我将相应地编辑问题,非常感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    除了加载firebase-functionsfirebase-admin 模块之外,您还需要初始化一个admin 应用实例,从中可以进行Cloud Firestore 更改,如下所示:

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    
    admin.initializeApp();
    
    //...
    

    我在您的 CF 中发现了另一个问题。您需要使用context 对象来获取id 的值。

    exports.updateGlobal = functions.firestore
      .document("/local/{id}")
      .onCreate((snapshot, context) => {
        
       const docId = context.params.id;
    
        return admin
          .firebase()
          .doc("global/" + docId)
          .update({
            total: admin.firestore.FieldValue.increment(1),
         });
      });
    

    您也可以使用template literals,如下:

        return admin
          .firebase()
          .doc(`global/${docId}`)
          //...
    

    【讨论】:

    • 非常感谢,虽然我之前尝试过这个,但那次没用,我知道为什么。无论如何,doc( "/collection/{id}" ) 是否与 collection("collection").doc("{id}") 一样工作?
    • 很高兴能帮到你!您也可以接受答案,请参阅stackoverflow.com/help/someone-answers。谢谢! “doc( "/collection/{id}") 是否与 collection("collection").doc("{id}") 工作相同”=> 是的,请参阅 googleapis.dev/nodejs/firestore/latest/Firestore.html#doc(“参数:文档的斜杠分隔路径。”)
    • 看到更新,发现需要使用context对象来获取id的值。
    猜你喜欢
    • 2019-06-04
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2022-11-14
    • 1970-01-01
    相关资源
    最近更新 更多