typescript - 有没有办法使用云功能将云 Firestore 连接到实时数据库?
问题描述
我正在以这样一种方式设计我的firebase数据库,即firestore中的某些文档字段链接到实时数据库字段;因此,如果实时数据库发生变化,它会更改相应的 firestore 字段。
让我给我的问题更多的背景。
我正在设计一个具有错误报告聊天室的移动应用程序。在这些聊天室中,用户可以编写他们的错误,并将他们的错误输入实时数据库以及更新 Firestore。
在管理员方面,他应该能够阅读他们所有的错误。
我还没有真正深入研究云功能,所以我想知道是否有可能以这种方式将两者联系起来。
以下是 Firestore 集合的结构:
解决方案
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!
推荐阅读
- python - 无法删除错误值的 ValueError [已关闭:已解决问题]
- python - 如何计算自上次事件==1 以来的天数?
- angular - 如何根据布尔值更改图像,其中布尔值存储在数据库中,图像存储在角度文件中
- r - 如何在 R 中输出固定距离值的单词的所有可能偏差?
- node.js - 在满足条件时取消所有量角器测试
- r - 设置最小值和最大值以绘制回归的预测值
- mysql - 为什么从表中删除行并在此之后插入新行时 id 不正确?
- microsoft-graph-api - createRequest 返回数组而不是类
- laravel - 关于 laravel API 的信息
- javascript - 如何找出脚本在 Firefox 控制台中运行的时间?