首页 > 解决方案 > 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);


  });

  });

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

解决方案


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


}



推荐阅读