简体   繁体   English

如何获取Firestore文档中的字段?

[英]How to get fields in a firestore document?

I am working on some Cloud functions that works with Firestore. 我正在研究与Firestore配合使用的某些Cloud函数。 I am trying to get a list of fields of a specific document. 我正在尝试获取特定文档的字段列表。 For example, I have a document reference from the even.data.ref , but I am not sure if the document contains the field I am looking at. 例如,我有一个来自even.data.ref的文档参考,但是我不确定文档是否包含我正在查看的字段。 I want to get a list of the fields' name, but I am not sure how to do it. 我想获取字段名称的列表,但是我不确定该怎么做。 I was trying to use Object.keys() method to get a list of keys of the data, but I only get a list of number (0, 1...), instead of name of fields. 我试图使用Object.keys()方法来获取数据键的列表,但是我只获得了数字列表(0,1 ...),而不是字段名。
I tried to use the documentSnapShot.contains() method, but it seems doesn't work. 我尝试使用documentSnapShot.contains()方法,但似乎不起作用。

exports.tryHasChild=functions.firestore.document('cities/{newCityId}')
.onWrite((event) =>{
  if (event.data.exists) {
    let myRef = event.data.ref;
    myRef.get().then(docSnapShot => {
      if (docSnapShot.contains('population')) {
        console.log("The edited document has a field of population");
      }
    });

As the documentation on using Cloud Firestore triggers for Cloud Functions shows, you get the data of the document with event.data.data() . 有关将Cloud Firestore触发器用于Cloud Functions的文档所示,您可以通过event.data.data()获得文档的数据。

Then you can iterate over the field names with JavaScript's Object.keys() method or test if the data has a field with a simple array check: 然后,您可以使用JavaScript的Object.keys()方法遍历字段名称,或通过简单的数组检查来测试数据是否包含字段:

exports.tryHasChild=functions.firestore.document('cities/{newCityId}')
.onWrite((event) =>{
  if (event.data.exists) {
    let data = event.data.data();
    Object.keys(data).forEach((name) => {
      console.log(name, data[name]);
    });
    if (data["population"]) {
      console.log("The edited document has a field of population");
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM