You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js Firebase Functions执行sendNotification时遇TypeError:无法读取user_id

Fixing "TypeError: Cannot read property 'user_id' of undefined" in Firebase Cloud Function

Hey there! Let's figure out why you're hitting that TypeError: Cannot read property 'user_id' of undefined error in your Firebase Cloud Function.

The Root Cause

It looks like you're using an older syntax for Firebase Cloud Functions. Starting from Functions v1.0 and above, the onWrite trigger's callback parameters changed. The old event object no longer contains the params property—instead, path parameters are now stored in the context argument that's passed as the second parameter to your callback.

On top of that, there's a small typo in your code: you're trying to access event.params.notification, but your database path uses {notification_id} as the wildcard. That variable name should match the wildcard you defined!

Fixed Code

Here's the corrected version of your code with these issues addressed:

'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');

// Newer versions of Firebase Admin don't require passing functions.config().firebase
admin.initializeApp();

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
 const user_id = context.params.user_id;
 const notification_id = context.params.notification_id; // Fixed variable name to match the wildcard
 console.log('The User Id is : ', user_id);
 console.log('The Notification Id is : ', notification_id);
 // Add your notification-sending logic here
});

Key Changes Explained

  • Callback Parameters: Switched from relying on event to using (change, context)—context.params is now the home for your path wildcards.
  • Admin Initialization: admin.initializeApp() no longer needs functions.config().firebase; Firebase automatically loads the correct configuration from your function's environment.
  • Variable Name Fix: Changed notification to notification_id to align with the {notification_id} wildcard in your database path.

This should resolve the "Cannot read property 'user_id' of undefined" error and get your function logging the correct values.


内容的提问来源于stack exchange,提问作者Ahmed Amine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:07:38