4
votes

How can I return a collection of documents from firestore database. For example, I have a collection named countries in cloud firestore, and I want to fetch all the country names and ids as json , like this

[
    {
        "countryId" : 1,
        "countryName" : "Any"
    },
    {
        "countryId" : 2,
        "countryName" : "India"
    }
]

Now I am doing a foreach on the snapshot. Is that the only way to convert a collection to json?

3

3 Answers

2
votes

What you're doing is correct. You have to iterate each document in the collection/query, and generate the JSON yourself from there. There is no single operation for converting a collection to some other format in its entirety.

0
votes

Try this approach

const db = admin.firestore();   
......
......
async function getCollection (req, res){ 
try{

  let result = await db.collection('collection_name').get(); //TODO: add query if needed
  let response = [];

  result.forEach(doc => {
    response.push(doc.data());
  });

  return res.send( { "collection" : response} );

 }catch(err){
  res.status(500).send(err);
 }

}
0
votes

There is a way to get the collection without loop.

const companies = async (req, res) =>{
    const {id} = req.query;
    db.collection("users")
        .where("role", "==", "vendor")
        .get()
        .then((querySnapshot) => {
            var docs = querySnapshot.docs.map(doc => doc.data());
            res.status(200).json(docs);
        });
}