Firebase 和 Firestore 的 Cloud Functions 入门

问题描述 投票:0回答:1

任何人都可以给我一些指导,让 Firestore 与 Cloud Functions 一起工作。

我正在尝试按照此处的文档进行操作:https://firebase.google.com/docs/firestore/extend-with-functions

使用

firebase deploy --only functions:_onFirestoreWrite_notifications

我收到消息:HTTP 错误:400,请求有错误

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

const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();

admin.initializeApp();

const db = admin.firestore();

exports._onFirestoreWrite_notifications = functions.firestore
  .document('_notifications')
  .onWrite((change, context) => {

  //..

  });
firebase google-cloud-platform google-cloud-firestore google-cloud-functions
1个回答
1
投票

根据以下 OP 的评论进行更新:显然在 Cloud Function 名称中使用下划线会导致问题

使用

onWrite()
触发器,您将触发对特定document 的任何更改的事件。 Firestore 中的文档存储在collections 中,因此您需要将文档的完整路径 传递给
document()
方法,如下所示:

exports.onFirestoreWriteNotifications = functions.firestore
  .document('collection/_notifications')  //Note the addition of the collection
  .onWrite()

另外,注意不需要做

const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();

因为在您的 Cloud Functions 中,您将使用 Admin SDK for Node.js 与 Firestore 交互。

这样做

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

herehere(Node.js 选项卡)所解释的那样就足够了。

然后您将使用

admin.firestore()
调用 Firestore 数据库,例如,
admin.firestore().collection('_hello').add({...})


另外,注意你必须返回异步任务返回的Promise。

如果我参考你的初始代码(在你编辑之前)

exports._onFirestoreWrite_notifications = functions.firestore
  .document('collection/_notifications')
  .onWrite((change, context) => {

    db.firestore//.collection('_hello').add({
      text: "itworks",
      from: "onWrite"
    });

  });

你需要做

return admin.firestore().collection('_hello').add({
  text: "itworks",
  from: "onWrite"
});
//!!! Note the return (and the use of admin.firestore() )

这是一个重点,在 Firebase 视频系列中有关“JavaScript Promises”的三个视频中得到了很好的解释:https://firebase.google.com/docs/functions/video-series/

© www.soinside.com 2019 - 2024. All rights reserved.