How to retrieve FCM Token and userId from database then send Push Notification with Node.js and Cloud Functions

Viewed 124

I'm very new to Node.js and I'm having trouble figuring out how to send a push notification.

This is my code so far.


const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.sendPushOrderOnTheWay = functions.https.onRequest((req, res) => {

    const userId = req.body.id;
    const registrationToken = ''

    db.collection('users').doc(userId).get().then(function (doc) {

        registrationToken = doc.data().registrationToken;
    });

    const payload = {
        token: registrationToken,
        notification: {
            title: 'Din levering er på vej!',
            body: 'Vi er der indenfor 30 min.'
        },
        data: {
            body: message,
        }
    };
    admin.messaging().send(payload).then((response) => {
        console.log('wuhuu:', response);
        return { success: true };
    }).catch((error) => {
        return { error: error.code };
    });
});

I know something is missing to make it work, but I can't seem to figure out what it is.

My problem:

I don't know how to properly get the userId and FCM token. Or if there are any other mistakes in my code.

This is my firestore structure:

Picture here

0 Answers
Related