Firebase: Cloud Firestore trigger not working for

2019-08-22 02:07发布

enter image description hereI 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 docments inside a collection??

/*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(event => {


//now i'm returning to my personal document and fetched my username only because i don't want to send a notification to myself, 
const fromUser = admin.firestore().collection("users").doc("iamrajesh@gmail.com").get();



//here i want to fetch all documents in the "users" collection
const toUser = admin.firestore().collection("users").document.get();//if i replace "docmument" with "doc("xxxxxxx@gmail.com")" it works it fetches his FCM but how to fetch all documents??


//All documents has a "username",and a fcm "token"

        return Promise.all([fromUser, toUser]).then(result => {
            const fromUserName = result[0].data().userName;
            const toUserName = result[1].data().userName;
            const tokenId = result[1].data().tokenId;

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

            return admin.messaging().sendToDevice(tokenId, notificationContent).then(result => {
                console.log("Notification sent!");
                //admin.firestore().collection("notifications").doc(userEmail).collection("userNotifications").doc(notificationId).delete();
            });
        });

});

1条回答
仙女界的扛把子
2楼-- · 2019-08-22 02:51

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;
  });

});
查看更多
登录 后发表回答