将查询快照中的文档作为JSON字符串Firestore返回 [英] Return documents in query snapshot as json string firestore
问题描述
我在节点中进行了一个查询以存储到Firestore以获取文档集合.我想将集合写为要由应用程序解析的json字符串.我的代码如下:
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}));
}
我以这种方式获取不必要的数据,因为我得到的只是文档快照.如何遍历文档快照并将其发送到一个json字符串中?
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?
推荐答案
QuerySnapshot
和 Document
类不是简单的JSON类型.如果要控制所写内容,则需要遍历 querySnapshot
(使用 map
或 forEach
)并提取JSON数据以用于你自己.
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.
一个可能的例子:
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}));
}
});
这篇关于将查询快照中的文档作为JSON字符串Firestore返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!