【问题标题】:Firebase functions: cannot read property 'user_id' of undefinedFirebase 函数:无法读取未定义的属性“user_id”
【发布时间】:2018-09-13 18:56:15
【问题描述】:

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

通知数据库如下所示:

【问题讨论】:

  • 所有来到这里的人请注意:您可能使用的是某些教程的旧版本,该教程尚未更新为使用 Cloud Functions for Firebase API 1.0 版的 API。请通知教程的创建者他们的内容已过时。

标签: node.js firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions


【解决方案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);

对于onWrite 和onUpdate 事件,数据参数具有before 和after 字段。其中每一个都是DataSnapshot,与admin.database.DataSnapshot中提供的方法相同


params

一个对象,其中包含路径参数中通配符的值,该参数提供给实时数据库触发器的 ref() 方法。

更多信息在这里:

Cloud functions v1.0 Changes

EventContext#params

Change

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-30
    • 2018-04-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多