Firebase 实时数据库模拟器:即使触发了 onWrite 函数,也无法从数据库中读取(快照始终为空)
Firebase Realtime Database Emulator: Can't read from database (snapshot is always null) even though onWrite function gets triggered
我在模拟器中有一个非常简单的云函数运行:
functions.region('europe-west1').database.ref('teams/{teamId}/members/{memberId}')
.onWrite(async (change, context) => {
const snapshot = await admin.database().ref('teams').once('value')
console.log(26, snapshot.exists())
console.log(snapshot.val())
})
当我在模拟器中更改成员或添加新成员时,会触发此功能(因此 'teams' 已 100% 定义)但是快照始终为空且不存在。
我正在使用以下命令启动模拟器:
firebase emulators:start --import ./folder
该文件夹有一个 JSON 文件和我的数据库。
任何人都知道是什么原因造成的?如此令人沮丧,从字面上看总是在控制台中看到 null。
您需要导出该函数,以便 运行 在本地 Firebase 模拟器中使用它。您还可以参考这些 documentation 了解执行环境的工作原理。
我已经重现了您提供的代码中的错误。以下是基于您给定代码的工作示例函数:
var admin = require("firebase-admin");
var functions = require("firebase-functions")
// Initialize the app with a service account, granting admin privileges
admin.initializeApp();
// As an admin, the app has access to read and write all data, regardless of Security Rules
exports.simpleDbFunction = functions.region('europe-west1').database.ref('teams/{teamId}/members/{memberId}')
.onWrite(async (change, context) => {
const snapshot = await admin.database().ref('teams').once('value')
console.log(26, snapshot.exists())
console.log(snapshot.val())
})
我在不同地区有两个不同的数据库实例。模拟器正在侦听数据库 A 中的更改,但正在读取数据库 B。我只模拟了数据库 A。
我在模拟器中有一个非常简单的云函数运行:
functions.region('europe-west1').database.ref('teams/{teamId}/members/{memberId}')
.onWrite(async (change, context) => {
const snapshot = await admin.database().ref('teams').once('value')
console.log(26, snapshot.exists())
console.log(snapshot.val())
})
当我在模拟器中更改成员或添加新成员时,会触发此功能(因此 'teams' 已 100% 定义)但是快照始终为空且不存在。
我正在使用以下命令启动模拟器:
firebase emulators:start --import ./folder
该文件夹有一个 JSON 文件和我的数据库。 任何人都知道是什么原因造成的?如此令人沮丧,从字面上看总是在控制台中看到 null。
您需要导出该函数,以便 运行 在本地 Firebase 模拟器中使用它。您还可以参考这些 documentation 了解执行环境的工作原理。
我已经重现了您提供的代码中的错误。以下是基于您给定代码的工作示例函数:
var admin = require("firebase-admin");
var functions = require("firebase-functions")
// Initialize the app with a service account, granting admin privileges
admin.initializeApp();
// As an admin, the app has access to read and write all data, regardless of Security Rules
exports.simpleDbFunction = functions.region('europe-west1').database.ref('teams/{teamId}/members/{memberId}')
.onWrite(async (change, context) => {
const snapshot = await admin.database().ref('teams').once('value')
console.log(26, snapshot.exists())
console.log(snapshot.val())
})
我在不同地区有两个不同的数据库实例。模拟器正在侦听数据库 A 中的更改,但正在读取数据库 B。我只模拟了数据库 A。