从 Firestore 检索 json 数据

2023-12-27

在 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 作为数据本身的一部分


根据https://cloud.google.com/nodejs/docs/reference/firestore/0.17.x/QuerySnapshot https://cloud.google.com/nodejs/docs/reference/firestore/0.17.x/QuerySnapshot and https://cloud.google.com/nodejs/docs/reference/firestore/0.17.x/QueryDocumentSnapshot https://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 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} with

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

PS:这将返回一个 Promise 对象而不是数组本身,所以你必须使用.then()在返回的 Promise 或新的 Promise 上await syntax

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Firestore 检索 json 数据 的相关文章

随机推荐