2

I am using nodeJS with firebase for my flutter/firebase mobile app

I would like to send notifications to all users that have a certain query met. ie all users who have radiology as their specialty. So that they will be notified when a new article is added to the database

However I am unsure why my code (below) doesn't work to get notification tokens for all users with this query.

My database structure is users/notificationTokens/Ids of all tokens for that user stored in field 'token'

exports.sendToDevice5 = functions.firestore
    .document('Articles/{paper}')
    .onCreate(async (snapshot, context) => {
      const paper = context.params.paper;

      const item = snapshot.data();

      if (item.subspecialty == "RadMSK" || item.subspecialty == "RadMS") {
        

        const tokens = await admin.firestore().collection('users').where("specialty", "==", "RADIOLOGY").get().then(
            snapshot.forEach((doc) => {
              const docs = admin.firestore().collection('users').doc(doc.id).collection('notificationTokens').get();
              return docs.data().token;
            }));

        const payload = {
          notification: {
            title: `${item.title}!`,
            body: `New Journal`,
            sound: "default",
          },
          data: {click_action: 'FLUTTER_NOTIFICATION_CLICK'},
        };

        return admin.messaging().sendToDevice(tokens, payload);
      }
    });
  • A number of things could be causing your code to fail, for example if `item.subspecialty` was "test" then it would silently fail. However, I think the bigger issue is the `.sendToDevice(tokens, payload);` will execute before the tokens var has been populated from Firebase. e.g. this appears to be an asynchronous issue. This [question and answer](https://stackoverflow.com/questions/52030741/node-firebase-oncall-asynchronous-function-return) may help. And maybe [this answer](https://stackoverflow.com/questions/50144428/nodejs-assigning-to-variable-data-retrieved-asynchronously-in-firebase) too – Jay Nov 13 '21 at 18:08

0 Answers0