Home > front end >  How to check if a document is empty in Firestore?
How to check if a document is empty in Firestore?

Time:11-20

I have the following DocumentReference:

const risultati = await firestore.collection("Risultati").doc("risultati").get();

This document always exists but sometimes has 0 fields. I'd like to check if the document is empty (no fields in it). I'm trying this code: risultati.data().length returning undefined

Screenshot of document:enter image description here

EDIT with further informations:

The function that deletes document's fields is the following:

exports.delete = functions.pubsub
  .schedule('55 3 * * *')
  .onRun(async (context) => {
  const risultati = await firestore.collection("Risultati").doc("risultati").get();
  for(id in risultati.data()){
    if(risultati.data()[id]!=0){
      await firestore.collection("Risultati").doc("risultati").update({
        [id]: fieldValue.delete()
      });

    }

  }



  return null;

});

The output of console.log(risultati.data()) is blank, as indicates the line following "function execution started". enter image description here

CodePudding user response:

You created a document with some fields and delete those fields, that's how you can end up with an empty document. As such, Firestore does not provide a function which can check if document is empty or not, but you can check it yourself.

if(Object.entries(doc.data()).length < 1){
      // your document is empty
}
  • Related