1
votes

I am trying to write a cloud function for the user to get notification. I have a Task model in which the user specifies a task and writes the email id of the other user he assigns the task to. enter image description here

When the above task is added it should send the notification to the user specified in field 'Taskgivento'

My user model is as follows enter image description here I have a users models having data of a user and a subcollection in it saving the fcm in token subcollection .the id of the subcollection is the fcm token.

My cloud function

export const sendToDevice = functions.firestore
  .document('Task/{TaskId}')
  .onCreate(async snapshot => {

   const Taskdata=snapshot.data()

   const querySnapshot = await db
      .collection('users')
      .doc('HMPibf2dkdUPyPiDvOE80IpOsgf1')
      .collection('tokens')
      .get();

    const tokens = querySnapshot.docs.map(snap => snap.id);

    const payload: admin.messaging.MessagingPayload = {
      notification: {
        title: 'New Order!',
        body: 'new notification',
        icon: 'your-icon-url',
        click_action: 'FLUTTER_NOTIFICATION_CLICK'
      }
    };

    return fcm.sendToDevice(tokens, payload);
  });

in the const queryshot i am trying to filter the user model to get thee fcm token such that the the uid it notifies the Taskgiven to emailid.

The above function works. I have manually written the uid in the above model . I need it to search the database and fill the uid of the email of taskgivento. How should i procceed I have tried writing where('email','=','Taskdata.Taskgivento') like we do in dart but of no use. it is giving an error.

1

1 Answers

3
votes

The following should do the trick:

export const sendToDevice = functions.firestore
    .document('Task/{TaskId}')
    .onCreate(async snapshot => {

        const Taskdata = snapshot.data()
        const email = Taskdata.Taskgivento;

        const userQuerySnapshot = await db
            .collection('users')
            .where('email', '==', email)
            .get();

        const userDocSnapshot = userQuerySnapshot.docs[0]; // Assumption: there is only ONE user with this email
        const userDocRef = userDocSnapshot.ref;

        const tokensQuerySnapshot = await userDocRef.collection('tokens').get();

        const tokens = tokensQuerySnapshot.docs.map(snap => snap.id);

        const payload: admin.messaging.MessagingPayload = {
            notification: {
                title: 'New Order!',
                body: 'new notification',
                icon: 'your-icon-url',
                click_action: 'FLUTTER_NOTIFICATION_CLICK'
            }
        };

        await fcm.sendToDevice(tokens, payload);
        return null;

    });

You need to:

  1. Get the user Document. Note the syntax of where('email', '==', email) with ==.
  2. Get the DocumentReference of this Document, and based on this Reference, query the tokens subcollection.