title: Push Notifications Using Firebase Cloud Functions in Firestore
body: <p>I am having trouble making a javascript code that will send a notification to the user. I have few questions and clarifications that I want to know:</p>
  
  <ul>
  <li>Why am i having an error like this. </li>
  </ul>
  
  <pre><code>TypeError: Cannot read property 'userID' of undefined
      at exports.sendNotification.functions.firestore.document.onWrite.event (/srv/index.js:8:30)
      at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
      at /worker/worker.js:825:24
      at &lt;anonymous&gt;
      at process._tickDomainCallback (internal/process/next_tick.js:229:7)
  </code></pre>
  
  <ul>
  <li>And about the <code>tokenID</code>, how will i implement it? One time insertions when the user sign up? or Every time the user logged in the token id will updated?</li>
  </ul>
  
  <p><strong>Below is my code on index.js:</strong></p>
  
  <pre><code>'use strict'
  
  const functions = require('firebase-functions');
  const admin = require('firebase-admin');
  admin.initializeApp(functions.config().firebase);
  
  exports.sendNotification = functions.firestore.document("Buyers/{userID}/Notifications/{notificationId}").onWrite(event =&gt; {
      const userID = event.params.userID;
      const notificationId = event.params.notificationId;
      console.log("BuyerID: "+userID);
  
  
      return admin.firestore().collection("Buyers").doc(userID).collection("Notifications").doc(notificationId).get().then(queryResult =&gt; {
      const notificationMessage = queryResult.data().notificationMessage;
      const notificationTitle = queryResult.data().notificationTitle;
  
      console.log("Title: "+notificationTitle);    
      console.log("Message: "+notificationMessage);    
  
      const toUser = admin.firestore().collection("Buyers").doc(userID).get();
  
          return Promise.all(toUser).then(result =&gt; {
              const tokenId = result[0].data().tokenId;
  
              const notificationContent = {
                  notification: {
                      title: notificationTitle,
                      body: notificationMessage,
                      icon: "default",
                      sound : "default"
                  } 
              };
  
          return admin.messaging().sendToDevice(tokenId, notificationContent).then(result =&gt; {
          console.log("Notification sent!");
          return null;
              });
          });
      })
  });
  </code></pre>
  
  <p><strong>And here is the sample structure of my database in firestore</strong>
  <a href="https://i.stack.imgur.com/On8wg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/On8wg.png" alt="enter image description here"></a></p>