[英]Return document collection as json from firestore
如何從 firestore 數據庫返回文檔集合。 例如,我在 cloud firestore 中有一個名為 countries 的集合,我想以 json 格式獲取所有國家/地區名稱和 ID,如下所示
[
{
"countryId" : 1,
"countryName" : "Any"
},
{
"countryId" : 2,
"countryName" : "India"
}
]
現在我正在對快照執行 foreach。 這是將集合轉換為 json 的唯一方法嗎?
你在做什么是正確的。 您必須迭代集合/查詢中的每個文檔,並從那里自己生成 JSON。 沒有單一的操作可以將一個集合完整地轉換成某種其他格式。
有一種方法可以不循環地獲取集合。
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);
});
}
試試這個方法
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.