【问题标题】:retrieve data from Firestore as json从 Firestore 检索数据为 json
【发布时间】:2019-05-03 07:50:57
【问题描述】:

在 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())

答案

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

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

【问题讨论】:

    标签: angular firebase google-cloud-firestore


    【解决方案1】:

    根据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/Array/map

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

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

    Object.assign(doc.data(), {id: doc.id});
    

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

    【讨论】:

    • 谢谢,但如果我需要带有数据的 ID 文档密钥,我必须将其推入数组!
    • 我已经用关于如何处理对象的基本知识更新了我的答案
    • 感谢它对我有用,但我已编辑您的代码以使 _id 作为数据本身的一部分
    猜你喜欢
    • 2020-06-22
    • 2019-09-24
    • 2021-06-16
    • 1970-01-01
    • 2021-05-21
    • 2020-04-04
    • 2021-02-22
    • 1970-01-01
    相关资源
    最近更新 更多