Madhavam Shahi
Madhavam Shahi

Reputation: 1192

How to read the latest document created in Firestore using node?

I wrote a cloud function, to listen for document creation in a collection, in my database

here is the function,

const functions = require('firebase-functions');
const admin = require('firebase-admin');
 
admin.initializeApp(functions.config().functions);
 
var newData;
 
exports.myTrigger = functions.firestore.document('FCM/{id}').onCreate(async (snapshot, context) => {
    //
 
    if (snapshot.empty) {
        console.log('No Devices');
        return;
    }
 
    newData = 'hello';
 
    const deviceIdTokens = await admin
        .firestore()
        .collection('FCM')
        .get();
 
 var tokens = [];
 var i=0;
    for (var token of deviceIdTokens.docs) {
        tokens.push(token.data().ar1[i]);
        i++;
    }
    var payload = {
        notification: {
            title: 'push title',
            body: 'push body',
            sound: 'default',
        },
        data: {
            push_key: 'Push Key Value',
            key1: newData,
        },
    };
 
    try {
        const response = await admin.messaging().sendToDevice(tokens, payload);
        console.log('Notification sent successfully');

        
    } catch (err) {
        console.log(err);
    }
});

This function works weirdly,

For example, sometimes it sends notification, and sometimes it does not.

I don't know how to resolve this issue,

In my arr1 field, i have an array of device tokens, to whom i want to send notifications to,

i want the function to send notifications only to the devices(using tokens) which are just created(in the newly created document ),then delete the document.

I think it's sending notifications to all the documents at once.

I'm pretty new at node..

Is there anyway to only send notifications to the device tokens present in only one document (..the latest created document)?.. I think it's sending notifications to all.

please help me out.

UPDATE:- Here is my document structure this isnmy document structure

Upvotes: 1

Views: 177

Answers (1)

JayCodist
JayCodist

Reputation: 2544

Firstly, in an onCreate handler, you can access the id of just the newly created document by through the snap object, you can access the id via snapshot.id and the body via snapshot.data().

You already have the newly created document fetched, so no need to fetch entire collection. You should replace this entire section:

const deviceIdTokens = await admin
.firestore()
.collection('FCM')
.get();
 
 var tokens = [];
 var i=0;
 for (var token of deviceIdTokens.docs) {
    tokens.push(token.data().ar1[i]);
    i++;
 }

with this:

const tokens = snapshot.data().ar1;

UPDATE: To delete the new document, you could do

await firestore().collection("FCM").doc(snapshot.id).delete();

since the new document belongs in the FCM collection, not "helpReqs"

Upvotes: 1

Related Questions