Node.js Firebase Functions执行sendNotification时遇TypeError:无法读取user_id
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
eventto using(change, context)—context.paramsis now the home for your path wildcards. - Admin Initialization:
admin.initializeApp()no longer needsfunctions.config().firebase; Firebase automatically loads the correct configuration from your function's environment. - Variable Name Fix: Changed
notificationtonotification_idto 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

