get object for all my documents in Cloud Firestore

时光毁灭记忆、已成空白 提交于 2020-07-09 19:56:44

问题


I want to send a JSON of all my docuements in Firestore from my backend created with express

The Firestore docs says how to get all documents but the method is with forEach and express can send only once the response. So the problem is that I don't know how to render all forEach in a variable to send once for the headers

This is the code of Firestore docs:

  db.collection('users').get()
    .then((snapshot) => {
      snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
      });
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });

I hope somebody can help me.


回答1:


You could for example create and populate a JavaScript object of type array:

  db.collection('users').get()
    .then((snapshot) => {
      var usersArray = [];
      snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
        usersArray.push(doc.data());
      });
      //do something with the usersArray
      //e.g. return usersArray;
      ///or return JSON.stringify(usersArray)
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });


来源:https://stackoverflow.com/questions/56322010/get-object-for-all-my-documents-in-cloud-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!