简体   繁体   English

将文档添加到云 Firestore 中的指定集合时如何更新文档?

[英]How to update a document when a document is added to a specified collection in cloud firestore?

I have 2 collections in my firestore (global and local) and when I add a doc to local I need to update a field in the global doc by 1我的 Firestore 中有 2 个 collections(全局和本地),当我将文档添加到本地时,我需要将全局文档中的字段更新 1

Below is the code I have for the same.下面是我的代码。 I am very new to this so I might have some syntactical error as well, please do highlight if you find any.我对此很陌生,所以我也可能有一些语法错误,如果你发现任何问题,请高亮显示。

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),
     });
  });

The Terminal says "function failed on loading user code" Before this, it showed something along the lines of "admin is undefined" or "cannot access firestore of undefined" which I'm unable to replicate now.终端显示“加载用户代码时功能失败”在此之前,它显示了类似于“管理员未定义”或“无法访问未定义的Firestore ”的内容,我现在无法复制。

This is a part of a react app which has normal firestore working through firebase npm module Any other info needed regarding the issue I'll edit the question accordingly, thank you so much for the help.这是反应应用程序的一部分,该应用程序具有通过firebase npm 模块正常工作的反应应用程序有关该问题的任何其他信息我将相应地编辑问题,非常感谢您的帮助。

In addition to loading the firebase-functions and firebase-admin modules, you need to initialize an admin app instance from which Cloud Firestore changes can be made, as follows:除了加载firebase-functionsfirebase-admin模块外,您还需要初始化一个admin应用实例,可以从中进行 Cloud Firestore 更改,如下所示:

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

admin.initializeApp();

//...

I see another problem in your CF.我在您的 CF 中看到另一个问题。 You need to use the context object to get the value of id .您需要使用context object 来获取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),
     });
  });

You can also use template literals as follows:您还可以按如下方式使用模板文字

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM