Search code examples
angulartypescriptfirebasegoogle-cloud-firestoreangularfire

To delete all documents from a firestore collection


I am trying to use this method:

deleteMessages(){
    this.firestore.collection("MESSAGES")
  .get()
  .then(res => {res.forEach(element => {element.ref.delete();});

      });
     }

But I receive the following error message :

Property 'then' does not exist on type 'Observable<QuerySnapshot>'.

Then I opted for the following:

deleteTheMessages() {
      const messagesCollection= this.firestore.collection<Message>('MESSAGES').get();
  
      messagesCollection.toPromise().then((snapshot) => {
        snapshot.forEach((doc) => doc.ref.delete());
      });
    }

toPromise was struck :

Then I had this message when tried to ng build

error: src/app/messages.service.ts:37:9 - error TS2532: Object is possibly 'undefined'.

37 snapshot.forEach((doc) => doc.ref.delete());

with ~~~~~~~~ under the word snapshot.

Couldn't solve both, so if you have any suggestion I will thankful.


Solution

  • The solution was to add a check-in as @Doug Stevenson suggested:

    if(snapshot)