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