【问题标题】:Getting started with Cloud Functions for Firebase and Firestore开始使用 Cloud Functions for Firebase 和 Firestore
【发布时间】:2019-05-08 10:14:54
【问题描述】:

谁能给我指点让 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.com/docs/functions/…
  • Firebase 部署错误,所以我想我在“导出”之前缺少了一些东西。允许 Firestore 运行
  • 请使用您正在运行的命令和来自“firebase deploy ...”的相应错误消息更新您的问题

标签: firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

更新以下 OP 的评论:显然在云函数名称中使用下划线会导致问题

使用onWrite() 触发器,您将触发对特定文档的任何更改的事件。 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({...})


另外,请注意,您必须返回异步任务返回的 Promises。

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

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/

【讨论】:

  • 嗨,感谢您选择它,但它的 functions.firestore 不起作用,我在发布之前尝试了不同的组合,但无法使其正常工作
  • 好的,现在我看到了问题:您需要使用父集合定义您的文档,例如 exports.myFunctionName = functions.firestore .document('collection_name/_notifications'')
  • 嗨,发现了问题...显然下划线导致了 firebase 函数中的问题,因此如果我将函数名称“_onFirestoreWrite_notifications”重命名为“onFirestoreWriteNotifications”,则我的函数名称有效
  • 很高兴听到@PHILLBOOTH!但我仍然认为您需要在文档路径中添加集合,如答案中所述。
  • 同意 .document('_notifications/{userID}')
猜你喜欢
  • 1970-01-01
  • 2021-04-13
  • 2018-04-04
  • 1970-01-01
  • 2017-09-07
  • 2018-01-03
  • 2022-12-01
  • 1970-01-01
  • 2018-10-16
相关资源
最近更新 更多