Currently, I play a bit with firebase and wanted to implement an increment and decrement mechanism. The current value should be stored in Cloud Firestore.
So I made a reference to it and check for the id and if the reference exists.
When I try to run the code I get back the correct id and payload.exist is true .
If I want now to add a check if the number is 0 to delete it, the Document Snapshot is unknown and so I can't find the property or call delete/update on the document.
Would be great if anyone could tell me how I get access to the data in the Document. Thanks! :)
Here you can find the attached code:
constructor(private db: AngularFirestore) { }
private updateNumberCount(count: number) {
const reference = this.db.collection('counting').doc('documentId');
reference.snapshotChanges().pipe(take(1)).subscribe(item => {
console.log(item.payload.id); // the correct id is displayed
console.log(item.payload.exists); // -> is true
const quantity = (item.currentNumber || 0) + count;
if (quantity === 0) {
// if it is 0 it should be deleted
item.delete();
} else {
// if it not exists it should be created or updated
item.update({ currentNumber });
}
});
}
As explained in the doc , snapshotChanges()
returns an Observable of data as a DocumentChangeAction
.
And for the DocumentChangeAction
type :
A
DocumentChangeAction
gives you the type and payload properties. ... The payload property is aDocumentChange
which provides you important metadata about the change and adoc
property which is theDocumentSnapshot
.
So the following should do the trick (untested):
const quantity = (item.payload.doc.data().currentNumber ...
I could get the data back by calling .ref.get().then() on the referance to the document.
const reference = this.db.collection('counting').doc('documentId');
reference.ref.get().then(doc => {
// here I can call **.data** on it to receive the data.
doc.data().currentNumber
}
Thank you for all the help! :)
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.