1
votes

I am trying to query another collection inside my firestore Cloud Function trigger event but it always return nothing, But when i tried querying inside that firestore trigger event it works

take a look

exports.newTicketNotification = functions.firestore
.document('tickets/{refNo}')
.onCreate(async (snap, context) => {

   //get user
   const user = snap.data().ticketOwnerUid

   // Here i tried to query a collection called fcmTokens(Where my fcmTokens are stored)
   // this returned no matching documents
   // but if i use this  db.collection('tickets').where('tickeOwnerUid', '==', user).get() it works 

    db.collection('fcmTokens').where('userUid', '==', user).get()
    .then(snapshot => {
      if (snapshot.empty) {
        console.log('No matching documents.');
        return;
      }  
      snapshot.forEach(doc => {
        console.log(doc.id, '=>', doc.data());
      });
    })
    .catch(err => {
      console.log('Error getting documents', err);
    });

});

I am using this so i can get the fcm token of the device and send a notification to them. is this the right way to do it? or you guys can recommend a better way Thank you in advance ;) Ps. I'm stuck for 2 days :(

1
Which value is assigned to the db variable? - Renaud Tarnec

1 Answers

0
votes

Note that you are using async/await and then() together.

The following should work:

exports.newTicketNotification = functions.firestore
.document('tickets/{refNo}')
.onCreate((snap, context) => {   //Note that we have removed async

   const db = admin.firestore();

   //get user
   const user = snap.data().ticketOwnerUid

   // Here i tried to query a collection called fcmTokens(Where my fcmTokens are stored)
   // this returned no matching documents
   // but if i use this  db.collection('tickets').where('tickeOwnerUid', '==', user).get() it works 

    return db.collection('fcmTokens').where('userUid', '==', user).get()
    .then(snapshot => {
      if (snapshot.empty) {
        console.log('No matching documents.');
        return;
      }  
      snapshot.forEach(doc => {
        console.log(doc.id, '=>', doc.data());
        //If you plan to call asynchronous methods, you should probably use Promise.all
      });
      return;
    })
    .catch(err => {
      console.log('Error getting documents', err);
      return;
    });

});

Note how we return the Promises chain, since the Cloud Function is a background triggered one. I would suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/ which explain this key point.