0

How do I check if a document exists in Firebase Firestore, if not create a new one.

this is my code for now:

create(doc: any, collection: string): any {
  this.db.collection(collection, ref => ref.where('nome', '==', doc.nome))
    .snapshotChanges()
    .subscribe((ref: any) => {
      console.log('Ref = ', ref);
      if (ref.length <= 0) {
        this.db.collection(collection).add({ ...doc }).then(
          res => console.log('Inserido com sucesso : ', res)
        ).catch(err => console.log('Erro : ', err));
      }
      else {
        console.log('Evento ja existe : ', ref);
      }
    }).unsubscribe();
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
xandeq
  • 1
  • 1
  • Take a look at this question, it might help: https://stackoverflow.com/a/52277401/13058371 .... but the idea as the doc says: *If the document does not exist, it will be created. If the document does exist, its contents will be overwritten with the newly provided data* – Remoo Jul 31 '22 at 12:52

1 Answers1

0

Did you consider using the doc.nome value as the document ID? If you do that, you won't need to use a query to find a document for the value, and can use a transaction to check-and-write atomically:

  1. Start the transaction
  2. Read the document
  3. If it doesn't exist yet, write the document
  4. Commit the transaction

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807