[英]Return document collection as json from firestore
How can I return a collection of documents from firestore database.如何从 firestore 数据库返回文档集合。 For example, I have a collection named countries in cloud firestore, and I want to fetch all the country names and ids as json, like this
例如,我在 cloud firestore 中有一个名为 countries 的集合,我想以 json 格式获取所有国家/地区名称和 ID,如下所示
[
{
"countryId" : 1,
"countryName" : "Any"
},
{
"countryId" : 2,
"countryName" : "India"
}
]
Now I am doing a foreach on the snapshot.现在我正在对快照执行 foreach。 Is that the only way to convert a collection to json?
这是将集合转换为 json 的唯一方法吗?
What you're doing is correct.你在做什么是正确的。 You have to iterate each document in the collection/query, and generate the JSON yourself from there.
您必须迭代集合/查询中的每个文档,并从那里自己生成 JSON。 There is no single operation for converting a collection to some other format in its entirety.
没有单一的操作可以将一个集合完整地转换成某种其他格式。
There is a way to get the collection without loop.有一种方法可以不循环地获取集合。
const companies = async (req, res) =>{
const {id} = req.query;
db.collection("users")
.where("role", "==", "vendor")
.get()
.then((querySnapshot) => {
var docs = querySnapshot.docs.map(doc => doc.data());
res.status(200).json(docs);
});
}
Try this approach试试这个方法
const db = admin.firestore();
......
......
async function getCollection (req, res){
try{
let result = await db.collection('collection_name').get(); //TODO: add query if needed
let response = [];
result.forEach(doc => {
response.push(doc.data());
});
return res.send( { "collection" : response} );
}catch(err){
res.status(500).send(err);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.