The acceptance of the previous answer raises concerns as it seems to lead to incorrect behavior, resulting in an infinite loop (snapshotChanges()
triggering update()
, which then triggers another snapshotChanges()
due to subscribing.) Additionally, the AngularFirestore syntax mentioned appears to be outdated, prompting the need for a different approach.
To address the desired behavior by the original poster (OP), it is advised to store the document ID within the document itself. When adding a new item, the use of add()
provides a DocumentReference
that contains the newly inserted item's ID.
An effective implementation example would involve:
create(user) {
return new Promise<any>((resolve, reject) => {
this.db
.collection('users')
.doc('type')
.collection('customer')
.add(user)
.then(res => {
this.updateUserId(res.id);
}, err => reject(err));
});
}
updateUserId(id: string) {
return this.db
.collection('users')
.doc('type')
.collection('customer')
.doc(id)
.set({ id: id }, { merge: true });
}
In this scenario, the user is first created, followed by updating the id
field of the user object immediately (as the Firestore document ID becomes available post insertion). This enables easy subsequent updates based on the user’s document ID.