我正在尝试使用我的移动应用程序执行一个简单的 hello world firebase 功能,我想记录用户 ID,以便我可以看到该功能是否有效。 这是我当前的 JavaScript 代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notifications/{user_id}').onWrite((event) => {
console.log('Testing stuff', event.params.user_id);
return;
});
当新数据写入特定数据库表时会触发,但会出现此错误:
TypeError: Cannot read property 'user_id' of undefined
at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:8:44)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
最佳答案
您需要安装最新的 firebase-functions 和 firebase-admin:
npm install firebase-functions@latest firebase-admin@latest --save
npm install -g firebase-tools
为了能够使用新的 API,请在此处查看更多信息:
https://firebase.google.com/docs/functions/get-started#set_up_and_initialize
改变这个:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notifications/{user_id}').onWrite((event) => {
console.log('Testing stuff', event.params.user_id);
进入这个:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{user_id}').onWrite((change, context) => {
console.log('Testing stuff', context.params.user_id);
For
onWrite
andonUpdate
events, the data parameter hasbefore
andafter
fields. Each of these is aDataSnapshot
with the same methods available in admin.database.DataSnapshot
params
An object containing the values of the wildcards in the path parameter provided to the ref() method for a Realtime Database trigger.
更多信息在这里:
关于node.js - Firebase 函数 : cannot read property 'user_id' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49647170/