0

I am trying to send a notification whenever a new update to my database takes place. I have the onUpdate side working but I am new to FCM and I am stuck at the sending the notification. The structure of the devices collection is:

+devices/
+tokenId/
-tokenId:njurhvnlkdnvlksnvlñaksnvlkak
-userId:nkjnjfnwjfnwlknlkdwqkwdkqwdd

The function that I have right now that gets stuck with an empty value of token is:

const functions = require('firebase-functions');
const admin = require("firebase-admin");

admin.initializeApp();

const db = admin.firestore();

const settings = { timestampsInSnapshots: true };
db.settings(settings);

.....

exports.fcmSend = functions.firestore
  .document(`chats/{chatId}`).onUpdate((change, context) => {

    const messageArray = change.after.data().messages;
    const message = messageArray[(messageArray.length-1)].content
    if (!change.after.data()) {
        return console.log('nothing new');
      }
    const payload = {
          notification: {
            title: "nuevo co-lab",
            body: message,
          }
        };
  
    return admin.database().ref(`/devices`)
         .once('value')
          .then(token => token.val())
          .then(userFcmToken => {
            console.log("Sending...", userFcmToken);
            return admin.messaging().sendToDevice(userFcmToken, payload)
          })
          .then(res => {
            console.log("Sent Successfully", res);
          })
          .catch(err => {
            console.log("Error: ", err);
          });
  
  });

I am not able to get the token from the database. It is null or undefined. Can anyone help me with this second part of the function? Thanks a lot in advance!

  • The `return admin.database().ref(`/devices`)` is reading from the Firebase Realtime Database, while your code is triggering on a change to Cloud Firestore. While both databases are part of Firebase, they are completely separate and have their own API and documentation. To learn how to read from Firestore, have a look at https://firebase.google.com/docs/firestore/query-data/get-data – Frank van Puffelen Jan 14 '20 at 14:23

1 Answers1

3

Thanks Frank for the tip! I managed to solve the problem with this code in case anybody needs it:

const payload = {
      notification: {
        title: "nuevo mensaje de co-lab",
        body: message,
      }
    };

       // Get the list of device tokens.
const allTokens = await admin.firestore().collection('devices').get();
const tokens = [];
allTokens.forEach((tokenDoc) => {
  tokens.push(tokenDoc.id);
});

if (tokens.length > 0) {
  // Send notifications to all tokens.
  return await admin.messaging().sendToDevice(tokens, payload);     
}else {
  return null;
}