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

如何从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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:18:03