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?
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}));
}
});
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())));
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With