首页 > 解决方案 > 有没有办法使用云功能将云 Firestore 连接到实时数据库?

问题描述

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

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

标签: typescriptfirebasefirebase-realtime-databasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


Using the Firebase Admin SDK you can very well, in a Cloud Function, write from one Firebase database service to the other database service, i.e. from the Realtime Database to Cloud Firestore or vice-versa.

You write in your question "(If) there's a change in the Realtime Database, it changes the corresponding Firestore field.".

Here is a simple example of code that shows how to write to a specific Firestore document upon change in the Realtime Database. We take the case where you write to a city/radio node in the Realtime Database and you want to update the corresponding radio document in Firestore.

It's up to you to adapt it to your exact case, in particular adapting the path that triggers the Cloud Function and the Firestore document and field(s) you want to update.

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

    });

Since you "haven't really delved that much into the Cloud Functions", I would suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/

Diving into the documentation is also a must!


推荐阅读