【问题标题】:Can't retrieve document data in Firebase Cloud Function无法在 Firebase Cloud Function 中检索文档数据
【发布时间】:2021-03-24 12:17:26
【问题描述】:

我已将此功能设置为等待新文档onCreate 事件。

我已检查我的文档字段是否正确: 这是我的收藏/文档的结构:users/{userID}/...

{
    appVersion: [String]
    displayName: [String]
    email: [String]
    isUserBlocked: [bool]
    lastOnline: [timeStamp]
    photoUrl: [String]
    uid: [String]
    ...
}

Function for detecting new documents
// detects new users added
exports.newUserCreated = functions.firestore
  .document("users/{userID}")
  .onCreate(async (snap) => {
    // New document Created

    const user = snap.data();

    console.log(user.displayName); // logs 'undefined'
    console.log(user.uid); // logs 'undefined

    return;
  });

这是 2 个 console.logs 的结果

【问题讨论】:

  • 如果您正在记录内容,您还应该显示这些代码行以及它们生成的特定输出。 “似乎没有显示任何字段”不是很具体 - 在查询中显示日志的具体输出。
  • 另外,你没有注意sentToDevice返回的promise,这样会导致其他消息无法发送的问题。该函数应返回一个仅在所有异步工作完全完成后才解析的承诺。
  • edit:显示带有来自 Object.keys 循环日志的日志行的图片。还将添加 then 和 catchs 到 sentToDevice。但我确信这与有效载荷错误无关。
  • 哪一行是每行日志代码的结果?请清楚这些记录代码行在您的函数中的位置,以及输出如何与这些行匹配。如果您有错误,您应该展开它们以更详细地显示。我建议将此代码缩减到不能按您期望的方式工作的最低限度,以便您可以更好地隔离问题。看起来您为了调试而处理了太多额外的东西。我强烈建议阅读:stackoverflow.com/help/minimal-reproducible-example
  • @DougStevenson 完成。

标签: node.js google-cloud-firestore google-cloud-functions firebase-cloud-messaging


【解决方案1】:

我注意到我的问题是什么,在创建文档后,我的应用正在更新文档,这可能与 firebase 功能有关。我的错。

编辑:修复了这个问题,问题仍然存在。我倾向于相信这是问题所在:

FirebaseFirestore.instance.collection('users').doc(_firebaseUser.uid).set(
          _userDataMap,
          SetOptions(merge: true), // <---- this merge option might be messing with the cloud function trigger
        );

我将对此进行测试并更新。

编辑:仍在测试为什么有时有效,有时无效。

目前这是我正在使用的 hack:

// detects new users added
exports.newUserCreated = functions.firestore
  .document("users/{userID}")
  .onCreate(async (snap) => {
    let sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

    // New document Created

    await sleep(500);

    // get admins if no admins return
    const adminUsers = await db
      .collection("users")
      .where("userType", "==", "admin")
      .get();

    if (adminUsers.empty) {
      return;
    }

    // console.log(snap.id);

    const thisDoc = await db.collection("users").doc(snap.id).get();

    var user;

    if (!thisDoc.exists) {
      console.log("No such document!");
      return null;
    } else {
      // console.log("Document data:", thisDoc.data());
      // Object.keys(thisDoc.data()).forEach((prop) =>
      // console.log(`key: ${prop}`)
      // );
      user = thisDoc.data();
    }

    // get and set data for notification/msg
    const payload = {
      notification: {
        title: "Nuevo Usuario Creado!",
        body: `Dar Acceso (Desbloquear) a ${user.displayName}?`,
        icon: user.photoUrl,
        click_action: "FLUTTER_NOTIFICATION_CLICK",
      },
      data: {
        userName: user.displayName,
        userID: user.uid,
      },
    };

    var adminTokens = [];
    // loop all admins get their token and send the notification/msg
    adminUsers.forEach((doc) => {
      adminTokens.push(doc.data().token);
    });

    admin
      .messaging()
      .sendToDevice(adminTokens, payload)
      .then((response) => {
        // Response is a message ID string.
        console.log("Successfully sent message:", response);
      })
      .catch((error) => {
        console.log("Error sending message:", error);
      });

    return null;
  });

基本上,它会检测到一个新文档,但由于我似乎无法从同一个文档中提取数据,因此我必须使用 get 方法来获取数据。 (是的,我知道它看起来很愚蠢,但它可以在 atm 工作)

【讨论】:

  • 我希望这不是一个长镜头,我一直在玩你的帖子的代码(那个更简单的那个)你能尝试广告.toString()吗?对我来说,这似乎是一个未定义的,因为它没有将其转换为字符串。也许你可以试试看?
  • 我的意思是添加 console.log(user.displayName.toString());每次都对我有用
  • @Luis Manual 如果您在 Firestore 上手动添加文档,它确实可以 100% 工作。但如果用 Flutter 应用程序完成,它似乎有问题。我不明白为什么。
  • 您知道,当您将文档添加到集合中时,新文档会像瞬间一样闪烁绿色。但是我的 Flutter 代码(与他们的 api 所说的相同)闪烁绿色的时间不到一秒钟。我相信它有问题。
  • 嘿,我一直在尝试与不同的客户...所以我不确定这是否可能是由于您的文档大小或根本原因...请你使用下一个日志只是为了验证?常量用户 = snap.data(); console.log(user.name.toString()); console.log(JSON.stringify(user)); // 这应该将对象作为一个整体打印出来......我只想看看它打印给你的是什么
猜你喜欢
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 2022-12-12
  • 2020-03-07
  • 2023-03-09
  • 1970-01-01
  • 2019-09-29
  • 2021-06-19
相关资源
最近更新 更多