Firestore如何从文档中获取键?

5
使用下面的查询,我可以获取文档并使用doc.data().name来获取键“name”的值。我想要获取该文档中的所有键。如何获取?
var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());

//**I want to get all keys in the document here.**

    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

1
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys - Linxy
2个回答

8

参考我在这个答案中的示例,你可以执行以下操作:

docRef.get().then(function(doc) {
    if (doc.exists) {
        let json = doc.data();
        console.log("Document data:", json);
        console.log("Document keys:", Object.keys(json));
        Object.keys(json).forEach((name) => {
          console.log(name, json[name]);
        });
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

0
在Firebase中,如果您想访问集合内文档中键的值。假设键为“name”或“email”。请使用以下代码:
searchSnapshot.docs[index]["name"].data()
searchSnapshot.docs[index]["email"].data()

注意:我在这里使用了搜索框,你可能有不同的插件来实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接