【问题标题】:Firebase: Cloud Firestore trigger not working for FCMFirebase:Cloud Firestore 触发器不适用于 FCM
【发布时间】:2023-03-22 14:47:01
【问题描述】:

我写这个是为了检测文档的变化,当它发生变化时,我想向集合中的所有用户发送通知“用户” 问题是如何选择集合中的所有文档??

/*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();
            });
        });

});

【问题讨论】:

    标签: javascript firebase firebase-cloud-messaging google-cloud-firestore google-cloud-functions


    【解决方案1】:

    以下应该可以解决问题。

    查看代码中的解释

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

    【讨论】:

    • 这很好用,同时我也尝试了 Topic Wise 发送给批量用户也有效,我认为 SendToTopic 限制为 1000,无论如何你的方法对我有用,非常感谢跨度>
    • 很高兴知道我可以帮助你!除了您的接受之外,如果您认为我的回答对您有帮助,您可以投票赞成 stackoverflow.com/help/privileges/vote-up。谢谢:-)!
    • 是的,兄弟赞成,但以前我把你的答案作为解决方案,我忘了赞成,对不起,谢谢
    猜你喜欢
    • 2020-10-15
    • 2016-01-17
    • 2020-04-24
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多