Push-уведомление — не получено всеми пользователями при отправке из firebase, получено только несколькими: FCM, ReactJS, Express.js

# #node.js #reactjs #mongodb #firebase #express

Вопрос:

Я пытался найти решение этой проблемы, как и везде. Даже выполнили шаги firebase для отправки сообщений на несколько устройств https://firebase.google.com/docs/cloud-messaging/js/send-multiple .Это вообще не сработало. Я хочу, чтобы уведомление с данным сообщением было отправлено всем присутствующим пользователям. Я попробовал шаги, указанные в документе firebase, но это не сработало. Даже когда я пытаюсь отправить уведомления с помощью localhost, они отправляются не всем пользователям, в которых присутствуют токены fcm. Он отправляется даже тому, чей токен fcm недействителен.

Это то, что я пробовал:

 var fcmAdmin = require('firebase-admin');
var _ = require('lodash');
var serviceAccount = JSON.parse(process.env.FCM_ACCOUNT_KEY);
var users = require('../models/schemas/user');

fcmAdmin.initializeApp({
    credential: fcmAdmin.credential.cert(serviceAccount)
});


pushNotification: async function (usersIds, message) {
    var userids = usersIds.map(user => user.toString());
    userids = _.uniq(userids);
    var registrationTokens = [];
    for (var i = 0; i < userids.length; i  ) {
        var user = await users.findById(userids[i], 'fcmTokens');
        if (user != null) {
            if (user.fcmTokens != null) {
                registrationTokens = registrationTokens.concat(user.fcmTokens);
            }
        }
    }
    registrationTokens = _.uniq(registrationTokens);
    if (message.apns == null) {
        message.apns = {
            payload: {
                aps: { sound: 'default', 'mutable-content': 1 }
            }
        };
    }
    let tokensAll = _.chunk(registrationTokens, 100);
    tokensAll.forEach(token => {
        message.tokens = token;
        fcmAdmin.messaging().sendMulticast(message)
            .then((response) => {
                logger.debug(response.successCount   ' messages were sent successfully');
            });
    });
}
 

usersIds здесь в коде находится ObjectId имя пользователя.

Мои данные в качестве образца:

     {"_id":{"$oid":"5f58b4f718d6ec00113a161b"},"fcmTokens":["c--72Sxu44w:APA91bHYLgSTuYv79MTi0McwOZmYEVFP3ytmT5OD6woUfjHTHEuDrqxwKiup8cSMaNkCbLBjklWJbWgFq6kJnk9AhpplV4AakD2hgcYP6xQecIyd47mKZgeIIY-z_0m2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SVW_HKLknscifCg84Z9zOF4cQG0dFL7sqHfaoMQF_zLwKGsPFQxlC4kZTSANX-f1xn08Mi3w6_Q6mdu7I2Zp4CXwIee8SFvp29Monnma7hKn43Csf9OxfSD"],"createdAt":{"$date":"2020-09-09T10:56:55.421Z"},"updatedAt":{"$date":"2021-09-16T10:59:25.544Z"},"__v":2283}
    
  
    
    {"_id":{"$oid":"5fa4effefeb0c4f920386bf0"},"__v":0,"fcmTokens":["f4yUoh4xIkA:APA91bFFnoXe_Qx0ny9B9IFPPehtRnSohjtbm-bYoVkpmu_v8m9Z1Bg0mzrjciyQ4oDQf4mCNPb2xPeQeka2s5Pau5nApvQJNYEsK8aaHTe6XYSFvxDEgVu9wj6RDNPeKG8PwQeRsHp9",
"fuJwizrKpKE:APA91bGyoYg9JkmmaV5Se0-gLuKB0bSja7KdLryrmFrTy6CocRFp5ft1HoUb7zG_3zS9cOkMUTDK1tO3R4_M0mrNLaDolAevrvxUCh3MzKhY6NokzIR0es311_OZ9mj68mDQQ1kDtTfR",
"fqoHivMnkA4:APA91bG_q_CFgA4GSs08kRAZkpMHzYCUuCDKzFyyQ01_YnvwUrGlsVOWaFspycvat59rztbDXMfhqdFfYt-0qtiQUaWU3uG8zIfZVxEWaidBB4FR6cdTLr_yhEklqeM83Z4rRAqREQcN",
"cM_Noa7OTWOEuKVIl1FRUU:APA91bEybvNf5ICeQJPOcaLMRNIJdD6qeULEIGrbkJqAXUcnH2x7dqKOmG2mMvhZAOromSCOit9M5rSn7NhaAH-NRh8BzNk224xzrTZkuBiTOEhiGhMCXltgaqclfRI_eHauIACW4E6c",
"dq5Tqwy6RGiWyJwNMsYU5V:APA91bGKZn6_7jlC_mTwGlDTdoS_nCDZ_GCf-xq60BpS1wwSh3IEKi4sCltHVY9bxOBd_tdyXlZYr2hWJMxXttleBRoRfT-HYowd0oWbeIXHyIH5ibGFODoW99ep-2ahzSwi18g59m9E",
"fT3ZF1DQL1U:APA91bHVbnXmcoJDfbA8HLDoszfBdWaZC5FK_GkxnF0g1qaQLjC4W5h1e6ekI7t66U_dA7Zc_Nu8Z0NmB6G-RSLhmUupqrcRk4-bqFXAfOW3wPaba1b-F1jwBKZJUpSF8NWbRg7rSsrw"]}
 

What I expect is atleast the message should be sent to all the fcm token which is present in tokensAll array, whether or not the token is expired or active. It should send the message to all the fcm tokens. In my case it does not happen. The successCount in my case is just 17. infact it should be 1036, as the count of unique fcm tokens are 1036. So 1036 fcm tokens should be receiving the message.

Question:

  1. Is there a way to remove all the invalid token before sending the the message to the user thus reducing the size of tokensAll ?
  2. How to send message to all the fcmtokens irrespective whether the fcm token is valid or invalid?

I do not know why this is happening. Need help here to tell me where I am going wrong.