Firebase函数:无法读取未定义的属性"user_id" [英] Firebase functions: cannot read property 'user_id' of undefined
问题描述
我正在尝试用我的移动应用程序做一个简单的hello world firebase函数,我想记录用户ID,以便可以看到该函数确实起作用. 这是我当前的javascript代码:
I am trying to do a simple hello world firebase function with my mobile app, I want to log the user ID so I can see that the function does work. This is my current javascript code:
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;
});
在将新数据写入特定的数据库表时会触发,但会显示此错误:
It does trigger when new data is written to specific databasetable but this error shows up:
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)
通知数据库如下所示:
The notification database looks like this:
推荐答案
您需要安装最新的firebase功能和firebase-admin:
npm install firebase-functions@latest firebase-admin@latest --save
npm install -g firebase-tools
要能够使用新的API,请在此处查看更多信息:
to be able to use the new API, check here for more info:
https://firebase.google.com/docs/functions/get-开始#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);
对于
onWrite
和onUpdate
事件,数据参数具有before
和after
字段.每个都是DataSnapshot
,具有与 admin中可用的相同方法.database.DataSnapshot
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
一个对象,该对象在提供给Realtime数据库触发器的ref()方法的path参数中包含通配符的值.
An object containing the values of the wildcards in the path parameter provided to the ref() method for a Realtime Database trigger.
更多信息在这里:
这篇关于Firebase函数:无法读取未定义的属性"user_id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!