小编典典

Firebase函数:无法读取未定义的属性“ user_id”

node.js

我正在尝试使用移动应用程序做一个简单的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)

通知数据库如下所示:
在此处输入图片说明


阅读 187

收藏
2020-07-07

共1个答案

小编典典

您需要安装最新的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);

对于onWriteonUpdate事件,数据参数具有beforeafter字段。每个都DataSnapshot具有admin.database.DataSnapshot中可用的相同方法


params

一个对象,该对象在提供给Realtime Database触发器的ref()方法的path参数中包含通配符的值。

更多信息在这里:

云功能v1.0更改

EventContext#params

更改

2020-07-07