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:
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.