How to get fields in a firestore document?

2019-08-12 09:12发布

I am working on some Cloud functions that works with Firestore. 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. 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.
I tried to use the documentSnapShot.contains() method, but it seems doesn't work.

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

1条回答
倾城 Initia
2楼-- · 2019-08-12 09:51

As the documentation on using Cloud Firestore triggers for Cloud Functions shows, you get the data of the document with 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:

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");
    }
});
查看更多
登录 后发表回答