【问题标题】:Firebase Cloud Function Query Not workingFirebase 云函数查询不起作用
【发布时间】:2019-02-04 12:27:59
【问题描述】:

我使用以下查询部署了一个函数:

admin.firestore().collection("fcm").where("devices",'array-contains', mobile).get().then((snapshots)=> {...});

这会从 Cloud Function Log 中返回以下错误:

msgTrigger: Function execution started

msgTrigger: Function returned undefined, expected Promise or value

msgTrigger: Function execution took 8429 ms, finished with status: 'ok'

msgTrigger: Unhandled rejection

msgTrigger: TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined at admin.firestore.collection.where.get.then (/user_code/index.js:23:65) at process._tickDomainCallback (internal/process/next_tick.js:135:7)

有人吗?

在这里与编辑战斗了好几天。决定分块发布我的功能代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var msgData;
var mobile;

第二部分:

exports.msgTrigger = functions.firestore
  .document('Messages/{MessageID}')
  .onCreate((snapshot, context) => {
      msgData = snapshot.data();
      mobile = msgData.mobile;

      admin.firestore().collection("fcm").where("devices", 'array-contains', mobile).get().then((snapshots) => {

第三部分:

var tokens = [];
if (snapshots.empty) {
  console.log('No devices');
} else {
  for (var token of snapshot.docs) {
    tokens.push(token.data().token);
  }
  var payLoad = {
    "notification": {
      "title": "de " + msgData.name,
      "body": "Alerta de Emergência!",
      "sound": "default",
      "icon": msgData.icon
    },
    "data": {
      "remetente": +msgData.name,
      "mensagem": "Alerta de Emergência!"
    }
  }

第四部分:

return admin.messaging().sendToDevice(tokens, payLoad).then((response) => {
console.log("mensagens enviadas");
}).catch((err) => {
console.log("erro: " + err);
});
}
});

});

【问题讨论】:

  • 您能分享一下您的云函数的整个代码吗?还有您使用的是哪个版本的 Firestore 和 Cloud Functions。
  • 很难通过编辑添加功能代码。一直说看起来我的帖子主要有代码,请添加一些额外的信息。但是,添加其他信息不会使错误消失。
  • @Renaud。我将功能分成几个部分,以便能够在此处发布(只是无法在 1 中将其发布到此处)。我正在使用 Firestore ^0.8.2+1, "firebase-admin": "~6.0.0", "firebase-functions": "^2.1.0"

标签: javascript firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

Firestore 0.8 是一个相当旧的版本,请参阅https://cloud.google.com/nodejs/docs/reference/firestore/0.8.x/。只有从 0.16 版开始,您才能使用 array-contains 查询运算符,请参阅 https://github.com/googleapis/nodejs-firestore/releases/tag/v0.16.0。所以你应该更新到最新版本。

我还调整了你的函数代码,首先(非常重要,见下文)返回第一个异步任务返回的承诺,然后在 if/then/else 中重新组织你的承诺链接。

现在可以正确执行了吗?

   const functions = require('firebase-functions');
   const admin = require('firebase-admin');
   admin.initializeApp();  // Here changed, see https://firebase.google.com/docs/functions/beta-v1-diff#new_initialization_syntax_for_firebase-admin

   exports.msgTrigger = functions.firestore
      .document('Messages/{MessageID}')
      .onCreate((snapshot, context) => {
        const msgData = snapshot.data();  //No need to declare this outside of the Cloud Function, see https://www.youtube.com/watch?v=2mjfI0FYP7Y
        const mobile = msgData.mobile;

        return admin.   // <- HERE return
          .firestore()
          .collection('fcm')
          .where('devices', 'array-contains', mobile)
          .get()
          .then(snapshots => {
            let tokens = [];
            if (snapshots.empty) {
              console.log('No devices');
              return null;
            } else {
              for (var token of snapshot.docs) {
                tokens.push(token.data().token);
              }
              var payLoad = {
                notification: {
                  title: 'de ' + msgData.name,
                  body: 'Alerta de Emergência!',
                  sound: 'default',
                  icon: msgData.icon
                },
                data: {
                  remetente: +msgData.name,
                  mensagem: 'Alerta de Emergência!'
                }
              };
              return admin.messaging().sendToDevice(tokens, payLoad);
            }
          })
          .catch(err => {
            console.log('erro: ' + err);
            return null;
          });
      });

为什么返回异步任务返回的承诺很重要?观看 Firebase 官方视频系列 (https://firebase.google.com/docs/functions/video-series/) 中有关“JavaScript Promises”的 3 个视频,以获得答案!

删除“.where('devices', 'array-contains', mobile)”会产生同样的错误。我将 msgData.name 和 msgData.mobile 添加到 console.log 并打印出来,所以第一部分很好:

1: 31: 05.140 AM
msgTrigger
Function execution started
1: 31: 11.289 AM
msgTrigger
Nome: Alan
1: 31: 11.291 AM
msgTrigger
mobile: 91983372845
1: 31: 11.291 AM
msgTrigger
erro: TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
1: 31: 11.297 AM
msgTrigger
Function execution took 6158 ms, finished with status: 'ok'

【讨论】:

  • 不幸的是,仍然显示“msgTrigger erro: TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined”。很抱歉一开始没有很清楚,我在 Flutter 应用程序中使用该功能。 Firestore ^0.8.2+1 位于 pubspec.yaml 中。 "firebase-admin": "~6.0.0" 和 "firebase-functions": "^2.1.0" 位于函数文件夹的 packages.json 中。我最近才安装了 firebase cli,所以我猜想安装了最新的 firestore-node.js 版本? nodejs = 6. 我应该应用什么更新?
  • 在 package-lock.json 我发现:"@google-cloud/firestore": { "version": "0.16.1",
【解决方案2】:

好吧,我终于找到了罪魁祸首:

for (var token of snapshot.docs) {

快照应该是快照。是的,这很令人尴尬,出色的 Firebase 支持团队向我指出了这一点。希望 Android Studio 能在 js 代码中识别出这种愚蠢的错别字。

仍然会标记 Renaud 的答案,因为他帮助优化了我的代码并在此过程中给了我一些有用的提示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-12
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多