Return documents in query snapshot as json string firestore

别来无恙 提交于 2020-03-22 06:37:27

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/53924257/return-documents-in-query-snapshot-as-json-string-firestore

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