title: Realtime Database Triggers and Push Notification Firebase and iOS
body: <p>I am following GitHub code on how to implement push notification based on realtime database triggers.  </p>
  
  <p>Here is the code and the link:</p>
  
  <p><a href="https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js" rel="nofollow noreferrer">https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js</a></p>
  
  <pre><code>/**
  * Copyright 2016 Google Inc. All Rights Reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
  'use strict';
  
  const functions = require('firebase-functions');
  const admin = require('firebase-admin');
  admin.initializeApp(functions.config().firebase);
  
  /**
  * Triggers when a user gets a new follower and sends a notification.
  *
  * Followers add a flag to `/followers/{followedUid}/{followerUid}`.
  * Users save their device notification tokens to       `/users/{followedUid}/notificationTokens/{notificationToken}`.
  */
  exports.sendFollowerNotification =    functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event =&gt;   {
  const followerUid = event.params.followerUid;
  const followedUid = event.params.followedUid;
  // If un-follow we exit the function.
  if (!event.data.val()) {
  return console.log('User ', followerUid, 'un-followed user', followedUid);
  }
  console.log('We have a new follower UID:', followerUid, 'for user:',    followerUid);
  
  // Get the list of device notification tokens.
  const getDeviceTokensPromise =     admin.database().ref(`/users/${followedUid}/notificationTokens`).once('value');
  
  // Get the follower profile.
  const getFollowerProfilePromise = admin.auth().getUser(followerUid);
  
  return Promise.all([getDeviceTokensPromise,    getFollowerProfilePromise]).then(results =&gt; {
  const tokensSnapshot = results[0];
  const follower = results[1];
  
  // Check if there are any device tokens.
  if (!tokensSnapshot.hasChildren()) {
    return console.log('There are no notification tokens to send to.');
  }
  console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
  console.log('Fetched follower profile', follower);
  
  // Notification details.
  const payload = {
    notification: {
      title: 'You have a new follower!',
      body: `${follower.displayName} is now following you.`,
      icon: follower.photoURL
    }
  };
  
  // Listing all tokens.
  const tokens = Object.keys(tokensSnapshot.val());
  
  // Send notifications to all tokens.
  return admin.messaging().sendToDevice(tokens, payload).then(response =&gt; {
    // For each message check if there was an error.
    const tokensToRemove = [];
    response.results.forEach((result, index) =&gt; {
      const error = result.error;
      if (error) {
        console.error('Failure sending notification to', tokens[index], error);
        // Cleanup the tokens who are not registered anymore.
        if (error.code === 'messaging/invalid-registration-token' ||
            error.code === 'messaging/registration-token-not-registered') {
          tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
        }
      }
    });
    return Promise.all(tokensToRemove);
  });
  });
  });
  </code></pre>
  
  <p>My silly question, new to Functions and Node, is in this code notifications are sent to all users who tokens are saved, is that correct?  and if it is how can I let's say send just to one particular person instead all? </p>
  
  <p>I was thinking of saving token of each user in different nodes (children) so I can pick the one I want to send notification to.  Does it work?</p>
  
  <p>Thanks All </p>