Firestore 如何从 Firestore 文档中获取密钥

Joh*_*ohn 2 javascript firebase google-cloud-firestore

使用下面的查询,我可以获取文档和 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);
});
Run Code Online (Sandbox Code Playgroud)

Fra*_*len 5

根据我这个答案中的示例,您可以执行以下操作:

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);
});
Run Code Online (Sandbox Code Playgroud)