简体   繁体   中英

How to get an array from Firestore with JavaScript?

In my below app I first get the uids of 4 players and then make a query for each username and the devices token id, that are stored separately in my database.

To save reads I stored both informations now in the same document in an array. Since I am a novice in JavaScript I don't know how to get this array now from Firestore and access the stored data in that array.

I know how to get an array from Firestore with Android/Java but this seems not to work with JavaScript.

Any help is much appreciated!

Here is my code that I use in a Cloud Function:


...

// 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)

      });

...

This is the log I get:


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

...

Here is the collection with the document that contains the array:

在此处输入图像描述

If I correctly understand your question, the following should do the trick:

      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];

      });

queryResult is a DocumentSnapshot : It "contains data read from a document in your Firestore database. The data can be extracted with.data() or.get() to get a specific field."

As explained in the documentation here you can access the data in your code using this

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

 console.log(queryResult.data());

});

i search on the internet for the same question but letter i found a great alternative of Firebase Array.

if you have problem with firebase array then

not use Firebase Array use Firebase maps in firestore that's help you to work similar with vanilla JavaScript Array

Visit Official Firebase Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM