Angular 以json格式从Firestore检索数据

Angular 以json格式从Firestore检索数据,angular,firebase,google-cloud-firestore,Angular,Firebase,Google Cloud Firestore,在firestore文档中,我找到了获取多个数据的方法 db.collection("cities").where("capital", "==", true) .get() .then(function(querySnapshot) { querySnapshot.forEach(function(doc) { // doc.data() is never undefined for query doc snapshots console.log(doc

在firestore文档中,我找到了获取多个数据的方法

db.collection("cities").where("capital", "==", true)
.get()
.then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
})
但这样我必须做两个循环,一个在后端处理数据并将其推入对象,然后在前端另一个循环显示数据!!是否有任何方法可以逃逸第一个循环并返回数据列表,而不在后端的循环中处理它

return res.status(200).json(doc.data())
答案

此答案将返回一个文档id,作为其自身所依据数据的一部分 和 没有直接的方法可以作为json对象直接获得结果。如果您想要数据列表的列表表示数组,那么您将不会使用id作为索引,我将使用数组映射函数:

如果不能使用es6语法,则将{…doc.data,id:doc.id}替换为


PS:这将返回承诺对象,而不是数组本身,因此您必须使用。然后在返回的承诺或新的等待语法上

谢谢,但如果我需要ID文档密钥和数据,我必须将其推入数组!我已经用如何处理对象的基本知识更新了我的答案,感谢它对我有用,但我已经编辑了你的代码,使_id成为数据本身的一部分
.get()
.then(query=>{
    let data = query.docs.map(doc=>{
        let x = doc.data()
            x['_id']=doc.id;
            return x;
    })
    res.status(200).json(data);
})
return db.collection("cities").where("capital", "==", true)
    .get()
    .then(function(querySnapshot) {
        return querySnapshot.docs.map(doc => {...doc.data(), id: doc.id});
    });
Object.assign(doc.data(), {id: doc.id});