从 Firestore 检索数据作为 json

Mah*_*poo 2 firebase angular 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.id, " => ", doc.data());
    });
})
Run Code Online (Sandbox Code Playgroud)

但是这样我必须在后端进行两个循环来处理并将数据推送到对象中,然后在前端进行另一个循环以显示数据!!有什么方法可以转义第一个循环并返回数据列表,而无需像那样在后端循环中处理它

return res.status(200).json(doc.data())
Run Code Online (Sandbox Code Playgroud)

答案

.get()
.then(query=>{
    let data = query.docs.map(doc=>{
        let x = doc.data()
            x['_id']=doc.id;
            return x;
    })
    res.status(200).json(data);
})
Run Code Online (Sandbox Code Playgroud)

这个答案将返回一个 doc id 作为数据本身的一部分

Dim*_* L. 5

根据https://cloud.google.com/nodejs/docs/reference/firestore/0.17.x/QuerySnapshothttps://cloud.google.com/nodejs/docs/reference/firestore/0.17.x/QueryDocumentSnapshot 那里不是直接将结果作为 json 对象获取的直接方法。如果你想要一个数据列表(列表意味着一个数组,所以你不会有 id 作为索引),我会使用数组map函数:https : //developer.mozilla.org/de/docs/Web/JavaScript/Reference /Global_Objects/阵列/地图

return db.collection("cities").where("capital", "==", true)
    .get()
    .then(function(querySnapshot) {
        return querySnapshot.docs.map(doc => {...doc.data(), id: doc.id});
    });
Run Code Online (Sandbox Code Playgroud)

如果您不能使用 es6 语法,则替换{...doc.data(), id: doc.id}

Object.assign(doc.data(), {id: doc.id});
Run Code Online (Sandbox Code Playgroud)

PS:这将返回一个 Promise 对象而不是数组本身,因此您必须.then()在返回的 Promise 或新await语法上使用