从实时数据库查询设备令牌后如何发送 Firebase 云消息

How to send Firebase cloud messaging after query device token from real time database

我想在从实时数据库成功查询设备令牌后发送通知

我的留言

  let push_token = [];
  let message = {
  message: {
  token: push_token,
  notification: {
    title: 'new post',
    body: title,
  },
  data: {
    post_id: id,
   },
  },
 };

查询令牌代码然后发送通知

admin
.database()
.ref('/devices_token')
.once('value', snapshot => {
  snapshot.forEach(function(data) {
    let val = data.val();

    push_token.push(val.fcmToken);
  });
})
.then(() => {
   admin.messaging
    .send(message)
    .then(response => {
      // Response is a message ID string.
      console.log('Successfully sent message:', response);
    })
    .catch(error => {
      console.log('Error sending message:', error);
    });
 });
});

控制台出错

TypeError: admin.messaging.send is not a function at admin.database.ref.once.then

正如您从 Admin SDK API 文档中看到的那样,admin.messaging 实际上是一个带有可选 App 参数和 returns Messaging 对象的函数。但是您的代码没有调用方法来获取对象。假设 send 是消息传递函数的 属性,但不存在这样的 属性。

你应该像这样使用它:

admin.messaging().send(...)

另请参阅 Firebase Admin documentation 以获取更多说明正确用法的代码示例。