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

Firebase云函数访问Firestore集合时FCM推送报错求助

问题分析与解决

核心错误点

  1. QuerySnapshot长度获取错误:Firestore的QuerySnapshot对象没有length属性,需用size获取文档数量,这是日志显示There are undefined tokens的直接原因。
  2. 未定义变量notificationTokens:代码中直接使用该变量但未赋值,导致遍历不存在的对象,进而child.token为undefined,触发FCM的必填字段错误。
  3. Firestore文档数据读取错误:需通过文档的data()方法获取内部字段,而非直接访问文档对象的属性。

修正后的代码

const {onSchedule} = require("firebase-functions/v2/scheduler");
const {getMessaging} = require("firebase-admin/messaging");
const {logger} = require("firebase-functions");
const {getFirestore} = require("firebase-admin/firestore");

const {initializeApp} = require("firebase-admin/app");
const tools = require("firebase-tools");

initializeApp();

exports.myFunction = onSchedule("* * * * *", async (event) => {
  const tokensRef = getFirestore().collection("myCollection");
  const tokensSnapshot = await tokensRef.get();

  if (tokensSnapshot.empty) {
    logger.log("There are no tokens to send notifications to.");
    return;
  }
  logger.log(`There are ${tokensSnapshot.size} tokens to send notifications to.`);

  const messages = [];
  // 遍历QuerySnapshot中的所有文档
  tokensSnapshot.forEach((doc) => {
    const tokenData = doc.data();
    const token = tokenData.token;
    // 校验token有效性,避免无效数据触发错误
    if (token) {
      logger.log(`token ${token} `);
      messages.push({
        data: {
          "fcmToken": token,
        },
        token: token,
      });
    } else {
      logger.log(`Document ${doc.id} has no valid token`);
    }
  });

  // 批量发送FCM消息的逻辑
  if (messages.length > 0) {
    try {
      const response = await getMessaging().sendAll(messages);
      logger.log(`Successfully sent ${response.successCount} messages`);
    } catch (error) {
      logger.error("Error sending messages:", error);
    }
  }
});

关键修正说明

  • 替换tokens.length为tokensSnapshot.size,正确获取Firestore集合的文档总数。
  • 用tokensSnapshot(QuerySnapshot实例)替代未定义的notificationTokens,通过forEach遍历每个文档。
  • 使用doc.data()读取文档的实际数据,再提取其中的token字段。
  • 新增token有效性校验,过滤无token的文档,避免触发FCM的必填字段错误。

内容的提问来源于stack exchange,提问作者DeKekem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 17:28:27