'Loop through firestore with cloud function

For push notification I have a collection called "users", where each document has information about one user. In each document is also the FCM-Token (as string value "token"), to send a message to this device. To reach each user I would like to get all FCM-Token, store it in an array and send it with a "sendToDevice"-Firebase function. It's a trigger, when a new document is created in the collection "Postings". But everytime I get an error.. I hope someone can help..?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

let afStore = admin.firestore()

var result: string[] = [];
var allToken: string[] = [];

exports.newPost = functions.region('europe-west3').firestore.document('/Postings/{id}').onCreate((snapshot: { data: () => any; }) => {

  var newValue: string;

  afStore.collection('Users').get().then((snap: any[]) => {
    snap.forEach((doc) => {
      allToken.push(doc.data()['token']);
    })
  }).then(() => {

    result = allToken.filter(element => {
      return element !== undefined
    });

    //You get the values of the newly created doc as follows:
    newValue = snapshot.data()['ueberschrift'];

    let payload = {
      notification: {
        title: newValue,
      },
    }

    admin.messaging().sendToDevice(result, payload)
      .then((response: string) => {
        console.log("Successfully sent message: ", response);
        return true;
      })
      .catch((error: string) => {
        console.log("Error sending message: ", error);
        return false;
      })
  })
});

Following error from firebase log: Error sending message: FirebaseMessagingError: Registration token provided to sendToDevice() at index 1 must be a non-empty string.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source