【发布时间】:2021-05-20 16:26:29
【问题描述】:
这几天我一直在追查这个问题,看来我在网上找到的所有参考资料都已过时并且不再相关,所以我非常感谢任何建议。
我有一个 Firebase 项目,它有一个实时数据库和云功能,可以监听这个数据库并写回更改等。我最近在同一个项目中添加了第二个数据库(更接近用户群),这个是相同的副本第一个,但我发现云功能没有按预期应用。 (默认数据库位于“us-central1”,第二个数据库位于“eurpoe-west1”,如果这有什么不同的话)
我发现此主题引用了相同的问题,但没有任何解决方案对我有用,并且引用的某些链接不再有效,因此我无法查看示例。 How to access multiple Realtime Database instances in Cloud Functions for Firebase
通过以下示例,我可以在第二个数据库中侦听更改,没有问题,
exports.exampleFunct = functions.region('europe-west1').database.instance('my_example-db-2').ref('/users/{uid}/requests/{request}').onCreate((req_snapshot, context) => {
//Do stuff in here. It works so far...
});
上述方法对第二个数据库有效,但是我无法使用 admin.database().ref().set() 或 admin.database() 读取/写入第二个数据库。 ref().once(...) .
例如,如果我想在上面的 exampleFunct 中使用此管理员调用加载用户的整个节点。
admin.database().ref("users/" + uid).once("value", (user_snap) => {
//Will only load default database.
});
上面这个方法只会读取我项目中的默认数据库,不会读取第二个数据库。
我已经尝试了上述函数的变体,将我的数据库 URL、数据库名称等传递到 database() 参数中,正如我在网上找到的其他一些解决方案中看到的那样,但没有一个适用我。根据云函数日志中错误的建议,我还尝试了在 URL 中使用和不使用 .europe-west1 引用。
-
admin.database("my_example-db-2").ref();
-
admin.database().instance("my_example-db-2").ref();
-
admin.database("https://my_example-db-2.firebaseio.com").ref();
-
admin.database("https://my_example-db-2.europe-west1.firebasedatabase.app").ref();
-
admin.database("https://my_example-db-2.firebasedatabase.app").ref();
我还尝试在初始化时传入数据库 url,如下所示。
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'https://my_example-db-2.europe-west1.firebaseio.com'//tried all variations of url.
});
我还尝试像这样设置第二个实例,
const db2 = admin.initializeApp({
databaseURL: "https://my_example-db-2.firebaseio.com"
}, 'db2');
...
admin.database(db2).ref();
但到目前为止,我无法读取/更新第二个数据库上的数据。
希望我没有胡扯太多。我的代码有很多其他的包袱,所以我尽量简化,如果有人能给我一些关于如何专门读/写第二个数据库的指示,我将非常感激。我觉得我错过了一些非常明显的东西。
谢谢。
##Update##
我也测试了下面Hiranya建议的方法,没有成功。
admin.initializeApp();
const defaultDb = admin.database();
// Get a reference to another DB in the same project.
const otherDb = admin.app().database('https://otherdb.firebaseio.com');
如果我使用我的数据库的 url https://my_example-db-2.firebasedatabase.app 部署上述建议,我会在部署时收到一条错误消息,
Error: Error occurred while parsing your function triggers.
Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com
firebaseio.com 不是我数据库的域,但如果我尝试 https://my_example-db-2.firebaseio.com 相反,它会部署得很好,但是当我在 firebase 控制台中测试函数并监控函数日志时,我发现它没有读取第二个数据库并且也给出了这个警告。 p>
[2021-02-18T11:47:41.596Z] @firebase/database: FIREBASE WARNING:
Namespace my_example-db-2 lives in a different region.
Please change your database URL to https://my_example-db-2.europe-west1.firebasedatabase.app (https://my_example-db-2.firebaseio.com)
我已经尝试了 URL 的所有变体但没有成功,所以这个解决方案似乎行不通。
【问题讨论】:
标签: node.js firebase-realtime-database google-cloud-functions firebase-admin