Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return documents in query snapshot as json string firestore

I have a query made in node to firestore to get a collection of document. I want to write the collection as a json string to be parsed by an application. My code is as follows:

serverRef = db.collection('servers');
        getDocs = serverRef.where('online', '==', true).get()
        .then(querySnapshot => {
            if (querySnapshot.empty) {
                res.send("NO SERVERS AVAILABLE");
            } else {
                var docs = querySnapshot.docs;
                console.log('Document data:', docs);
                res.end(JSON.stringify({kind: 'freeforge#PublicServerSearchResponse',servers: docs}));
            }

I get unnecessary data this way as all I get is document snapshots. How do I loop through the document snapshots and send them in one json string?

like image 715
Sammi3 Avatar asked Dec 25 '18 17:12

Sammi3


Video Answer


2 Answers

The QuerySnapshot and Document classes are not simple JSON types. If you want to control what is written, you'll need to loop over querySnapshot (with map or forEach) and extract the JSON data for yourself.

One possible example:

serverRef = db.collection('servers');
getDocs = serverRef.where('online', '==', true).get()
.then(querySnapshot => {
    if (querySnapshot.empty) {
        res.send("NO SERVERS AVAILABLE");
    } else {
        var docs = querySnapshot.docs.map(doc => doc.data());
        console.log('Document data:', docs);
        res.end(JSON.stringify({kind: 'freeforge#PublicServerSearchResponse', servers: docs}));
    }
});
like image 114
Frank van Puffelen Avatar answered Oct 31 '22 13:10

Frank van Puffelen


Anyone looking for flutter answer is this,

    serverRef = db.collection('servers');
    getDocs = serverRef.where('online', '==', true).get()
     .then(querySnapshot => {
       if (querySnapshot.empty) {
          res.send("NO SERVERS AVAILABLE");
          } else {
         var docs = 
         querySnapshot.docs.map(json.decode(json.encode(doc.data())));
       }
     });
like image 26
Saurabh Patwal Avatar answered Oct 31 '22 14:10

Saurabh Patwal