在 Firebase 云函数中访问 Firestore 集合

问题描述 投票:0回答:1

如何访问 firestore 集合:

这是我的代码:

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 tokens = await tokensRef.get();

  if (tokens.isEmpty) {
    logger.log("There are no tokens to send notifications to.");
    return;
  }
  logger.log(`There are ${tokens.length} tokens` +
  " to send notifications to.");

  const messages = [];
  notificationTokens.forEach((child) => {
    logger.log(`token ${child.token} `);
    messages.push({
      data: {
        "fcmToken": child.token,
      },
      token: child.token,
    });
  });

....

在云功能日志资源管理器上我收到此错误:

错误:需要主题、令牌或条件之一

我自己的日志如下:

token undefined
There are undefined tokens to send notifications to.

我基本上使用云函数教程中的一个示例代码作为灵感,但他们使用实时数据库。

child.token

中的
token是集合中的一个字段。

javascript google-cloud-functions firebase-cloud-messaging firebase-admin
1个回答
0
投票

我设法修复了它。

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

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

  const messages = [];
  notificationTokens.forEach((child) => {
    messages.push({
      data: {
        "fcmToken": doc.data().token,
      },
      token: doc.data().token,
    });
  });
    logger.log(`There are ${messages.length} tokens` +
      " to send notifications to.");
      const batchResponse = await messaging.sendEach(messages);
© www.soinside.com 2019 - 2024. All rights reserved.