如何从Firestore文档获取数组存入Node.js并作为token发送推送通知
问题排查与解决
核心问题
Firestore 的 get() 是异步操作,你没有等待该操作执行完成就直接运行了发送通知的代码,此时tokens数组还没有被填充数据,因此触发空token报错。
修正后代码
// 确保你的云函数入口是 async 修饰的,例如: // exports.sendMsgNotification = functions.firestore.document('xxx/{docId}').onCreate(async (snapshot, context) => { const newData = snapshot.data(); console.log("Retrieving Receiver Id"); console.log(newData.receiverId); //uid of the user const tokens = []; const docRef = db.collection('userdata').doc(newData.receiverId); try { // 等待文档读取完成 const doc = await docRef.get(); if (doc.exists) { console.log("DocRef exist"); const userToken = doc.data().tokens; // 直接合并数组,无需遍历push tokens.push(...userToken); } else { console.log("No such document!"); } } catch (error) { console.log("Error getting document:", error); } //Notification Payload const payload = { notification: { title: newData.sendBy, body: 'Sent you a message', sound: 'default', }, data: { click_action : 'FLUTTER_NOTIFICATION_CLICK', route: '/telconsultinbox', } }; console.log("Sending Notification now."); console.log(tokens); // 增加非空判断,避免无有效token时报错 if (tokens.length === 0) { console.log("No valid tokens, skip sending notification"); return null; } try{ //send to device const response = await admin.messaging().sendToDevice(tokens, payload); console.log('Notification sent successfully'); console.log(newData.sendBy); } catch(err){ console.log(err); } // })
额外优化建议
- 如果你的
userdata文档中的tokens字段本身就是数组类型,不需要用for...in遍历,直接展开合并即可 - 增加tokens数组长度判断,无有效token时直接跳过发送逻辑,减少无用报错
- 统一使用
async/await语法,比then()回调更容易控制异步逻辑顺序
内容的提问来源于stack exchange,提问作者christian
相关产品推荐
相关产品推荐

