Sam*_*mi3 2 node.js firebase google-cloud-firestore
我在firestore的节点中进行了查询,以获取文档集合。我想将集合写为要由应用程序解析的json字符串。我的代码如下:
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}));
}
Run Code Online (Sandbox Code Playgroud)
我这样获得不必要的数据,因为我得到的只是文档快照。如何遍历文档快照并将其发送到一个json字符串中?
在QuerySnapshot和Document类不是简单的JSON类型。如果要控制所写的内容,则需要遍历querySnapshot(使用map或forEach)并自己提取JSON数据。
一个可能的例子:
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}));
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1504 次 |
| 最近记录: |