【问题标题】:Is there a way to connect cloud firestore to realtime database using Cloud functions?有没有办法使用云功能将云 Firestore 连接到实时数据库?
【发布时间】:2020-03-12 06:43:57
【问题描述】:

我正在设计我的 firebase 数据库,使 firestore 中的某些文档字段链接到实时数据库字段;因此,如果实时数据库发生变化,它会更改相应的 firestore 字段。

让我给我的问题更多的背景..
我正在设计一个具有错误报告聊天室的移动应用程序。在这些聊天室中,用户可以编写他们的错误,并将他们的错误输入实时数据库以及更新 Firestore。
在管理员方面,他应该能够阅读他们所有的错误。
我还没有真正深入研究云功能,所以我想知道是否可以以这种方式将两者联系起来。
以下是 Firestore 集合的结构:

【问题讨论】:

  • 您应该能够将所有数据存储在实时数据库或 Cloud Firestore 中。虽然两者之间的镜像是可能的,但请确定您需要实施这样一个系统的原因。记录的错误是否有任何原因无法保存到 Cloud Firestore?管理控制台用于管理数据,但不一定会使用它。开发一个在线网页(例如 HTTPS 函数/托管)来自定义数据的显示方式,以便更容易阅读错误、查看堆栈跟踪等,因此您只需要一个数据库或另一个。
  • 您能否提供一个需要镜像的数据示例?例如Firestore 中的 /users/user - lastError: ... 需要与 RTDB 中的 /errors/someError 进行镜像。
  • 两个数据库之间的双向镜像将很难正确实现。请考虑只进行单向镜像,并强制所有客户端仅写入一个数据库而不是同时写入。

标签: typescript firebase firebase-realtime-database google-cloud-firestore google-cloud-functions


【解决方案1】:

使用Firebase Admin SDK,您可以很好地在 Cloud Function 中从一个 Firebase 数据库服务写入另一个数据库服务,即从实时数据库到 Cloud Firestore,反之亦然。

您在问题中写道“(如果)实时数据库发生变化,它会更改相应的 Firestore 字段。”。

这是一个简单的代码示例,展示了如何在实时数据库中发生更改时写入特定的 Firestore 文档。我们假设您写入实时数据库中的city/radio 节点,并且您想更新 Firestore 中相应的radio 文档。

您可以根据具体情况对其进行调整,特别是调整触发 Cloud Function 的路径以及您要更新的 Firestore 文档和字段。

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

admin.initializeApp();

exports.updateFirestore = functions.database.ref('cities/{cityId}/{radioId}')
    .onWrite((change, context) => {

        const city = context.params.cityId;
        const radio = context.params.radioId;

        // Exit when the data is deleted -> to confirm that this is needed in your case....
        if (!change.after.exists()) {
            return null;
        }
        // Grab the current value of what was written to the Realtime Database.
        const data = change.after.val();

        //Write to Firestore: here we use the TransmitterError field as an example
        const firestoreDb = admin.firestore();
        const docReference = firestoreDb.collection(city).doc(radio);

        return docReference.set(
            {
                TransmitterError: data.TransmitterError
            },
            { merge: true }
        );

    });

由于您“还没有真正深入研究 Cloud Functions”,我建议您观看 Firebase 视频系列中有关“JavaScript Promises”的 3 个视频:https://firebase.google.com/docs/functions/video-series/

潜入documentation 也是必须的!

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2022-12-20
    相关资源
    最近更新 更多