James Gitonga
James Gitonga

Reputation: 101

loop through documents in a collection to get fields

I have a collection called users in firebase firestore. Each document in the collection users is a user registered in the app. Each document has a field called token_ids. How can I loop through all the documents to get the values in the token_ids field. I am using firebase cloud functions to do so. Here is the code snippet I tried using but it did not work:

const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp();

  //fetch all token ids of users

  const tokenReference = admin.firestore().collection("users");

  const tokenSnapshot  = await tokenReference.get();

  tokenSnapshot.forEach((doc) =>{

    console.log("Token ids are:" + doc.data().token_id);


  });

  });

Upvotes: 2

Views: 3894

Answers (3)

James Gitonga
James Gitonga

Reputation: 101

Took me a while but finally found the solution to it. Here it is. It is the first solution given by Dhruv Shah but slightly modified :

async function fetchAllTTokenIds() {

  const tokenReference = admin.firestore().collection("users");
  
  const tokenSnapshot  = await tokenReference.get();
  const results = [];
  tokenSnapshot.forEach(doc => {

    results.push(doc.data().token_id);

  });

  const tokenIds = await Promise.all(results);

  return console.log("Here =>" +tokenIds);


}


Upvotes: 3

Aqil
Aqil

Reputation: 21

How the code snippet will be structured depends whether you're using the Firebase Admin SDK, be it as a script ran on your local machine or a httpsCallable being called by a client app. For the first case, it is written like this:

In your script file.js, after initialising app, write the following code.

exports.test_f = async function() {
  try {

    const tokenReference = admin.firestore().collection("users");

    const tokenSnapshot  = await tokenReference.get();

    tokenSnapshot.forEach((doc) =>{

      console.log("Token ids are:" + doc.data().token_id);


    });
  } catch (error) {
    console.log(error);
  }
}

exports.test_f();

Run this script on your command line using the command node file.js, which will print the provided output

Upvotes: 0

Dhruv Shah
Dhruv Shah

Reputation: 1651

Since Firestore operations are asynchronous, you should ideally wrap your code in an async-await block.

For example:

async function fetchAllTTokenIds() {

  const tokenReference = admin.firestore().collection("users");
  
  const tokenSnapshot  = await tokenReference.get();
  const results = [];
  // Recommendation: use for-of loops, if you intend to execute asynchronous operations in a loop.
  for(const doc of tokenSnapShot) {
    results.push(doc.data().token_id);
  }
  const tokenIds = await Promise.all(results);
}

In this way all the tokenIds variable will be populated with an array of tokenIds.

Alternatively, you can also make all the asynchronous calls in parallel since they are independent of each other using Promise.all (Reference)

async function fetchAllTTokenIds() {

  const tokenReference = admin.firestore().collection("users");
  
  const tokenSnapshot  = await tokenReference.get();

  const tokenIds = await Promise.all(tokenSnapShot.map(doc => {
    return doc.data()
      .then(data => (data.token_id)) 
  }))

In this case, the tokenIds variable will contain the array of all the tokenIds.

Upvotes: 2

Related Questions