I have a flutter food ordering app which contains "Orders" table in Firebase Realtime Database. Here's the structure of the orders table.

orders/userId/oderId

enter image description here

I want to send a notification to a particular user via Firebase UID whenever any new order is created. I know the User UID of my admin user. I just don't know how to use this UID to send notification to this particular user.

Here's my code so far:

const admin = require("firebase-admin");

admin.initializeApp(); 
exports.myFunction = functions.database.instance("bb-9bb36")
    .ref("orders/{userId}/{id}")
    .onCreate((snapshot, context) => {  
      console.log(snapshot.val());               // I can see the data submitted under Functions -> Logs
      console.log("Inside push notification");  //I can see this logs under Functions -> Logs
    });


Solution 1: Aion

In order to do what you want, you need to register a token from your client (client side) and save it to it's firestore document.

I dont know what you are using Front Side so I'll show you how I did that in ionic :

import { FCM } from '@ionic-native/fcm/ngx';

// ...
const token = await this.fcm.getToken();

and save that token as a field in your user document.

After that, in your Firebase Cloud Function, use :

import * as admin from 'firebase-admin';

async sendNotif(userId: string) {

const payload = {
    notification: {
      'the title of the notif',
      'the body of the notif',
      sound: 'default',
      click_action: 'FCM_PLUGIN_ACTIVITY',
    },
    data: {
      command,
    },
  };
  const userSnap = await admin.firestore().collection('user').document(userId);
  admin.messaging().sendToDevice(userSnap.data().token, payload);
}

EDIT : For Flutter you can use :

import 'dart:io';
import 'package:flutter/material.dart';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class MessageHandler extends StatefulWidget {
  @override
  _MessageHandlerState createState() => _MessageHandlerState();
}

class _MessageHandlerState extends State<MessageHandler> {
  final Firestore _db = Firestore.instance;
  final FirebaseMessaging _fcm = FirebaseMessaging();

    // TODO... (configuration for your project ...

}

and to get the token :

    // Get the token for this device
    String fcmToken = await _fcm.getToken();