简体   繁体   English

如何使用 FCM 发送通知?

[英]How to send notification using FCM?

I wrote a cloud function, to listen for document creation in a collection, in my database我写了一个云function,在我的数据库中侦听集合中的文档创建

here is the function,这里是 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,这个 function 工作很奇怪,

For example, sometimes it sends notification, and sometimes it does not.例如,有时它会发送通知,有时则不会。

It throws errors like " TypeError: Cannot read property '0' of undefined".它会引发类似“TypeError:无法读取未定义的属性'0'”的错误。

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,在我的 arr1 字段中,我有一组设备令牌,我想向其发送通知,

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.我希望 function 仅向刚刚创建的设备(使用令牌)发送通知(在新创建的文档中),然后删除该文档。

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.所以我只能说有时 token.data() 没有 arr1 属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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