I need to join two tables in Firebase Firestore DB. Do do so, I have to get a value from collection 'attendees' and then perform a forEach
to recover the event data in collection 'event', pushing it into an array and then return the array in a promise.
I am using .valueChanges().subscribe()
. What happens here is, if I add a new event for this attendee, the subscription works and push the data into the array again.
What I need to know, is how with join table work. Is there any way to perform the forEach with no subscription?
Thanks!
EDIT
This is my collection combination to perform the join
findByUserUid(user_uid: string) {
let events: any[] = [];
console.log(events);
return new Promise((resolve, reject) => {
console.log(events);
this.db
.collection('attendees', ref => ref.where('user_uid', '==', user_uid))
.snapshotChanges()
.subscribe((attendeesSnaps: any) => {
events = [];
attendeesSnaps.forEach((attendeeSnapshot: any) => {
this.db
.collection('events')
.doc(attendeeSnapshot.payload.doc.data().event_uid)
.valueChanges()
.subscribe((event: any) => {
console.log(events);
event.uid = attendeeSnapshot.payload.doc.data().event_uid;
events.push(event);
console.log('pushing', event);
});
});
});
console.log('all events', events);
resolve(events);
});
}
When collection 'attendees' is updated (adding a new attendee to -this- event), the foreach is perfom again and I got duplicate data in events
array (which is returned again because of the subscription).
I need to avoid this duplicate data to be returned in every collection update.
EDIT 2
I've fixed the issue. Using .ref.get()
works fine! Here is my final version of the method (if it can be improved, please let me know :) )
findByUserUid(user_uid: string) {
const events: any[] = [];
return new Promise((resolve, reject) => {
this.db
.collection('attendees')
.ref.where('user_uid', '==', user_uid)
.get()
.then((attendeesSnaps: any) => {
attendeesSnaps.forEach((attendeeSnapshot: any) => {
this.db
.collection('events')
.doc(attendeeSnapshot.data().event_uid)
.ref.get()
.then((eventSnap: any) => {
const event = eventSnap.data();
event.uid = eventSnap.id;
events.push(event);
})
.catch(err => {
reject(err);
});
});
})
.catch(err => {
reject(err);
});
resolve(events);
});
}