【问题标题】:Firestore how to get keys from firestore documentFirestore 如何从 Firestore 文档中获取密钥
【发布时间】:2018-03-23 12:36:50
【问题描述】:

使用下面的查询,我可以获取文档和 doc.data().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);
});

【问题讨论】:

标签: javascript firebase google-cloud-firestore


【解决方案1】:

根据我在answer 中的示例,您可以这样做:

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);
});

【讨论】:

    【解决方案2】:

    在 firebase 中,如果您想访问集合内文档中某个键的值。假设键“名称”或“电子邮件”。使用下面的代码:

    searchSnapshot.docs[index]["name"].data()
    searchSnapshot.docs[index]["email"].data()
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多