如何 link FCM 向 node.js 与 mongoDB 连接的服务器发送消息?

How to link FCM messaging to a server node.js connected with mongoDB?

我目前正在从事一个项目,我想在其中向一组设备发送推送通知。在我的 node.js/express.js 后端中,我有定义要向哪个设备发送通知的代码。这些设备由存储在 mongoDB 数据库中的 ID 标识。

我做了很多研究,似乎唯一可用的选择是使用 Google 的 Firebase API。我完成了将 API 集成到我的应用程序中所需的所有步骤,但有一件事我仍然不明白。

当我有我的 mongoDB id 设备列表时,我应该如何将它们 link 到 Firebase 用来识别设备的令牌?

我的前端应用程序是用 Vue.js 和 Ionic 开发的。这是一款旨在跨平台的移动应用程序,但起初我只关注 Android

非常感谢您的帮助

使用这个包:

https://www.npmjs.com/package/fcm-notification

const fcm = require('fcm-notification');

var fcm_key = require('your/fcm/token/from/firebase');
var FcM = new fcm(fcm_key);

module.exports.sendToSingleUser = async (message, token) => {
    let message_body = {
        notification: {
            ...message
        },
        token: token
    };
    FcM.send(message_body, function (err, response) {
        if (err) {
            return err
        } else {
            return response
        }
    })

}

hint: get fcm tokens from clients and store them in the database.

此问题将指导您如何访问 android 设备或​​ ios 设备上的令牌。 请记住,您可以将令牌存储在用户模型中。像这样: sequilioze 示例:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const FCM_customer = sequelize.define('FCM_customer', {
    platform: {
      type: DataTypes.ENUM,
      values: ['android', 'apn', 'webpush']
    },
    deviceId: DataTypes.STRING,
    token: DataTypes.STRING
  }, {});
  FCM_customer.associate = function (models) {
    FCM_customer.belongsTo(models.Customer)
  };
  return FCM_customer;
};

Firebase (FCM) how to get token

额外:

  1. 将客户端应用程序注册到 firebase(本机开发人员任务:Andriod,ios)
  2. 客户端应用大多向后端提供fcm令牌。(原生开发者tasks:you可以在ios和Andriod平台搜索获取fcm令牌)
  3. 后端会将令牌存储在用户模型中。
  4. firebase 只知道令牌。然后使用 fcm 库发送到您想要的特定令牌

hint: there is a better solution which is: create a collection about devices of the clients. every client could have more than one device on other platforms.