Firestore触发Cloud Function发送推送通知时遇TypeError错误求助
解决Firestore Cloud Function的TypeError: Cannot read properties of undefined (reading 'name')错误
问题描述
在使用Cloud Function基于Firestore存储的token、通知时间等信息发送推送通知时,触发以下错误:
TypeError: Cannot read properties of undefined (reading 'name') at beforeSnapshotConstructor (/workspace/node_modules/firebase-functions/lib/v1/providers/firestore.js:109:93) at changeConstructor (/workspace/node_modules/firebase-functions/lib/v1/providers/firestore.js:113:40) at cloudFunction (/workspace/node_modules/firebase-functions/lib/v1/cloud-functions.js:80:34) at /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/function_wrappers.js:98:17 at process.processTicksAndRejections (node:internal/process/task_queues:77:11)
完整Cloud Function代码:
exports.scheduleNotifications = functions.firestore .document('users/{userId}') .onUpdate(async (change, context) => { const newData = change.after.data(); const oldData = change.before.data(); console.log('New data:', newData); console.log('Old data:', oldData); // Check if newData and oldData exist and are objects if (!newData || !oldData || typeof newData !== 'object' || typeof oldData !== 'object') { console.log('Invalid data format. Exiting function.'); return null; // Exit function if data is missing or not in expected format } // Get notificationTime from newData and oldData const newNotificationTime = newData.notificationTime; const oldNotificationTime = oldData.notificationTime; // Check if notificationTime has been updated if (newNotificationTime !== oldNotificationTime) { console.log('Notification time updated. New time:', newNotificationTime); // Validate notificationTime format if (typeof newNotificationTime === 'string' && newNotificationTime.includes(':')) { // Parse notificationTime string into Date object const [hours, minutes] = newNotificationTime.split(':'); const scheduledTime = new Date(); scheduledTime.setHours(parseInt(hours, 10)); scheduledTime.setMinutes(parseInt(minutes, 10)); scheduledTime.setSeconds(0); scheduledTime.setMilliseconds(0); console.log('Scheduled time:', scheduledTime); const currentTime = new Date(); console.log('Current time:', currentTime); // Compare current time with scheduled time if (currentTime >= scheduledTime) { // Send FCM notification const message = { notification: { title: 'Your Daily Affirmation', body: 'This is your scheduled notification message.', }, token: newData.fcmToken, // Use the FCM token from the user document }; console.log('Sending FCM message:', message); await admin.messaging().send(message); console.log('Scheduled notification sent successfully to user:', context.params.userId); } else { console.log('Scheduled notification is not yet due for user:', context.params.userId); } } else { console.log('Invalid or missing notificationTime format:', newNotificationTime); } } else { console.log('Notification time has not changed.'); } });
即使简化为以下代码,错误仍未消失:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); const firestore = admin.firestore(); exports.scheduleNotifications = functions.firestore .document('users/{userId}') .onUpdate(async (change, context) => { });
解决步骤
1. 修复依赖版本兼容性
该错误大多源于firebase-functions与firebase-admin版本不匹配或过旧:
- 查看当前依赖版本:
npm list firebase-functions firebase-admin - 升级到兼容的最新稳定版:
npm install firebase-functions@latest firebase-admin@latest - 同步更新Firebase CLI:
npm install -g firebase-tools
2. 规范函数部署流程
确保使用Firebase CLI标准命令部署:
firebase deploy --only functions:scheduleNotifications
避免使用第三方部署工具,防止环境变量或依赖加载异常。
3. 验证触发器路径配置
确认users/{userId}路径正确,Firestore中存在users集合,且文档ID格式符合预期。
4. 本地模拟器测试
使用Firebase Emulator Suite排查云端环境问题:
- 启动模拟器:
firebase emulators:start --only functions,firestore - 更新Firestore中的
users文档,观察函数日志是否正常运行。
5. 检查Node.js版本兼容性
确保项目使用的Node.js版本符合firebase-functions要求(推荐v18或v20),可在package.json中指定:
"engines": { "node": "18" }
内容的提问来源于stack exchange,提问作者great8
相关产品推荐
相关产品推荐

