l return 如何从 Cloud Functions 中的字段值获取令牌?

How do l return the token from a field value in a Cloud Functions?

我收到此错误: 提供给 sendToDevice() 的注册令牌必须是非空字符串或非空数组。 在 FirebaseMessagingError.FirebaseError [作为构造函数] (/workspace/node_modules/firebase-admin/lib/utils/error.js:44:28)

exports.mediZim = functions.firestore.document("users/{user}/responses/{pharmacy}")
    .onCreate((change, context) => {
        const myData = change.data();
        const tokens = [];
        fstore.collection("pharmacies").doc(myData.uid).collection("userTokens").get().then((snap) => {
            return snap.forEach((element) => {
                tokens.push(element.data().token);
            });
        });
        return fcm.sendToDevice(tokens, {
            data: {
                title: "Medi-Zim",
                body: change.data().message,
                sound: "default",
            },
        });
    });

在“users/{user}/responses/{pharmacy}”我有这个 Firestore Field uid available

我使用 uid 获取另一个集合中的文档 ID,以便我可以获取馈入该文档的用户令牌。 l 然后发送想要发送的通知给tokens。 Error with eslint after trying answers 1 and 2 Another Try From answer 1

这是我从 Cloud Functions 得到的错误:

提供给 sendToDevice() 的注册令牌必须是非空字符串或非空数组。 在 FirebaseMessagingError.FirebaseError [作为构造函数] (/workspace/node_modules/firebase-admin/lib/utils/error.js:44:28)

return 语句在循环完成并且标记在数组中之前执行。

请尝试下面完全相同的代码,如果有效请告诉我。

exports.mediZim = functions.firestore.document("users/{user}/responses/{pharmacy}")
    .onCreate(async (change, context) => {
        const myData = change.data();
        const tokens = [];
        const tokenDocs = await fstore.collection("pharmacies").doc(myData.uid).collection("userTokens").get()
        tokenDocs.docs.forEach((doc) => {
            tokens.push(doc.data().token);
        });
        return fcm.sendToDevice(tokens, {
            data: {
                title: "Medi-Zim",
                body: change.data().message,
                sound: "default",
            },
        });
    });

我使用了 async-await 而不是链式承诺。现在应该等待 Firestore 的响应,然后 return FCM 函数。

这里的问题不在于令牌,而在于 async 代码。

试试这样的代码:

exports.mediZim = functions.firestore
  .document("users/{user}/responses/{pharmacy}")
  .onCreate((change, context) => {
    const myData = change.data();

    return fstore
      .collection("pharmacies")
      .doc(myData.uid)
      .collection("userTokens")
      .get()
      .then((snap) => {
        const tokens = [];

        snap.forEach((element) => {
          tokens.push(element.data().token);
        });

        return fcm.sendToDevice(tokens, {
          data: {
            title: "Medi-Zim",
            body: change.data().message,
            sound: "default",
          },
        });
      });
  });

您的代码存在问题,您没有等待 get 调用完成就返回了 fcm.sendToDevice。所以你总是将通知发送到一个空数组并得到那个错误。