Cloud Functions触发onUpdate时报change.after.get is not a function错误
报错原因与修复方案
核心报错原因
TypeError: change.after.get is not a function 是因为你混淆了 Firebase Realtime Database 和 Firestore 的快照接口用法:
Realtime Database 触发的 Cloud Functions 回调中,change.after 属于 DeltaSnapshot 类型,本身没有get()方法——get()是 Firestore 快照对象的专属方法,调用不存在的方法就会抛出该错误。
修复方法
替换获取字段的写法即可,有两种常用实现:
方式1:先取全量数据再提取字段
调用val()方法获取监听路径下的全部数据,再提取对应属性,建议增加空值判断避免后续FCM推送报错:
exports.sendNotification = functions.database.ref('/drivers/{wilayaid}/{driverid}/proposed').onUpdate(async (change) => { // 获取路径下全量数据 const proposedData = change.after.val(); const fcm = proposedData?.fcm; // 空值判断,没有有效token直接返回 if (!fcm) { console.log('未获取到有效的FCM token,终止推送'); return null; } const message = { notification: { title: "CLIQUE ICI", body: "NOUVELLE OFFRE DE TRANSPORTATION", }, token: fcm, } const response = await admin.messaging().send(message); console.log('推送成功:', response); // 原代码此处的fcmToken未定义,已删除避免额外报错 });
方式2:单独取子节点数据
如果只需要单个子节点的值,可以用child()方法定位后再取值:
const fcm = change.after.child('fcm').val();
其他注意点
你原代码末尾打印的fcmToken变量没有定义,运行到该位置会抛出未定义错误,需要删除或者替换为实际存在的变量名。
内容的提问来源于stack exchange,提问作者Qassim babyDroid
相关产品推荐
相关产品推荐

