简体   繁体   中英

How to send notification using FCM?

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.

It throws errors like " TypeError: Cannot read property '0' of undefined".

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..

please help me out.

UPDATE:- Here is my document structure

这是我的文档结构,

Type error coming from this line:

tokens.push(token.data().arr1[i]);

So all I can say is that sometimes token.data() doesn't have an arr1 attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM