Skip to content Skip to sidebar Skip to footer

Firebase: Cloud Firestore Trigger Not Working For FCM

I wrote this to detect a docment change,when it changes i want to send notifications to all the users who all are inside the Collection 'users' the problem is How to choose all doc

Solution 1:

The following should do the trick.

See the explanations within the code

/*eslint-disable */
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification23 = functions.firestore.document("student/anbu").onWrite((change, context) => {
  // Note the syntax has change to Cloud Function v1.+ version (see https://firebase.google.com/docs/functions/beta-v1-diff?0#cloud-firestore)

  const promises = [];
  let fromUserName = "";
  let fromUserId = "";

  return admin.firestore().collection("users").doc("iamrajesh@gmail.com").get()
  .then(doc => {
      if (doc.exists) {
         console.log("Document data:", doc.data());
         fromUserName = doc.data().userName;
         fromUserId = doc.id;
         return admin.firestore().collection("users").get();
      } else {
         throw new Error("No sender document!");
         //the error is goinf to be catched by the catch method at the end of the promise chaining
      }
   })
  .then(querySnapshot => {
     querySnapshot.forEach(function(doc) {

       if (doc.id != fromUserId) {  //Here we avoid sending a notification to yourself

         const toUserName = doc.data().userName;
         const tokenId = doc.data().tokenId;

         const notificationContent = {
               notification: {
                    title: fromUserName + " is shopping",
                    body: toUserName,
                    icon: "default",
                    sound : "default"
               }
         };

         promises.push(admin.messaging().sendToDevice(tokenId, notificationContent));

       }

     });

     return Promise.all(promises);

  })
  .then(results => {
    console.log("All notifications sent!");
    return true;
  })
  .catch(error => {
     console.log(error);
     return false;
  });

});

Post a Comment for "Firebase: Cloud Firestore Trigger Not Working For FCM"