【问题标题】:Using onCreate with Firebase Cloud Functions in Nested collection在嵌套集合中使用 onCreate 和 Firebase 云函数
【发布时间】:2020-04-24 16:28:13
【问题描述】:

我希望创建一个 Firebase 云函数,每次创建文档时都会调用该函数。使用他们的教程,我有以下代码:

exports.sendConfirmationEmail = functions.firestore.document('collection1/{resId}')
    .onCreate((snap, context) => {
      // my method
    });

现在每次将文档添加到 collection1 时都会调用此方法。但我有一个如下所示的数据库结构:

|企业

| => 商业文件

| => |预订

不确定这是否有意义,但基本上有一个业务集合,其中每个业务文档都包含一个预订子集合。我需要编写一个函数,每次将文档添加到每个业务的预订集合时都会执行该函数,但仍然能够以某种方式访问​​业务文档。我怎样才能做到这一点?感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    您的函数定义将如下所示:

    exports.yourFunctionName =
    functions.firestore.document('businesses/{businessId}/reservations/{reservationId}')
    .onCreate((snap, context) => {
        // your code goes here
    });
    

    【讨论】:

    • snap.data() 会对应预订吗?另外,我如何访问业务,因为关键是能够访问预订和业务文档。感谢您的快速回复!
    • 它将引用触发该功能的文档。如果您需要其他文档,则必须单独查询。
    • 好的,那我怎样才能得到businessId的值以便查询呢?
    • 请将 Stack Overflow 上的每个帖子限制为一个问题。我认为您的很多问题都将包含在文档中。 firebase.google.com/docs/functions/firestore-events
    • 谢谢,我找到了我正在寻找的代码 sn-p。您介意我编辑您的答案以包含它还是希望我创建一个新答案?
    【解决方案2】:

    对于其他任何人来说,这里是尝试检索业务和预订时的样子:

    exports.getReservationFromBusiness = functions.firestore.document('businesses/{bisId}/reservations/{resId}')
        .onCreate((snap, context) => {
          const businessId = context.params.bisId;
          const reservation = snap.data();
        });
    

    此代码来自documentation 和 Github page

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 2018-09-14
      • 2021-02-07
      • 2020-08-29
      • 1970-01-01
      • 2019-03-22
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多