【问题标题】:How to get an array from Firestore with JavaScript?如何使用 JavaScript 从 Firestore 获取数组?
【发布时间】:2020-05-27 06:10:29
【问题描述】:

在我下面的应用程序中,我首先获取 4 个玩家的 uid,然后查询每个用户名和设备令牌 ID,它们分别存储在我的数据库中。

为了保存读取,我现在将这两个信息存储在一个数组中的同一个文档中。由于我是 JavaScript 新手,我现在不知道如何从 Firestore 获取此数组并访问该数组中存储的数据。

我知道如何使用 Android/Java 从 Firestore 获取数组,但这似乎不适用于 JavaScript。

非常感谢任何帮助!

这是我在云函数中使用的代码:


...

// This is where the array is stored, I now need to get the array and access the data of it
      admin.firestore().collection("User").doc(uid_player_1).collection("User Info").doc("UsernameToken").get().then(queryResult =>{
        // You need to get the array that is stored there. The first value (0) there is the username, the second is the device token

console.log(queryResult)

      });

...

这是我得到的日志:


QueryDocumentSnapshot {
  _fieldsProto: 
   { usernameToken: { arrayValue: [Object], valueType: 'arrayValue' } },

...

这里是包含该数组的文档的集合:

【问题讨论】:

  • 您显示的文档似乎与您查询的文档不匹配。他们有不同的路径。
  • @DougStevenson 我编辑了我的帖子。现在您会看到我正在查询的文档,其中包含图像中的数组
  • 你能展示一下你在执行这一行时得到了什么console.log(queryResult)

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


【解决方案1】:

如果我正确理解了您的问题,以下应该可以解决问题:

      admin.firestore().collection("User").doc(uid_player_1).collection("User Info").doc("UsernameToken").get().then(queryResult =>{

          const username = queryResult.data().usernameToken[0];
          const token = queryResult.data().usernameToken[1];

      });

queryResultDocumentSnapshot:它“包含从 Firestore 数据库中的文档读取的数据。可以使用 .data() 或 .get() 提取数据以获取特定字段。”

【讨论】:

【解决方案2】:

如文档 here 中所述,您可以使用此访问代码中的数据

admin.firestore().collection("User").doc(uid_player_1).collection("User Info").doc("UsernameToken").get().then(queryResult =>{

 console.log(queryResult.data());

});

【讨论】:

    【解决方案3】:

    我在互联网上搜索相同的问题,但我发现了 Firebase Array 的绝佳替代品。

    如果您对 firebase 数组有疑问,那么

    不使用 Firebase 数组在 Firestore 中使用 Firebase 地图,这有助于您使用类似的原生 JavaScript 数组工作

    Visit Official Firebase Documentation

    【讨论】:

      猜你喜欢
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 2012-11-15
      相关资源
      最近更新 更多