首页 > 解决方案 > 如何使用 JavaScript 从 Firestore 获取数组?

问题描述

在我下面的应用程序中,我首先获取 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' } },

...

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

在此处输入图像描述

标签: javascriptnode.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


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

      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() 提取数据以获取特定字段。”


推荐阅读