简体   繁体   中英

Check if a document exists in Firebase Firestore, if not create a new

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM