I have two collections: "vehicles" and "clients". In each vehicle, I'm registering the client via client's document Id. I need to access the client's title using the key I'm storing in the vehicle document and display it in the Material DataTable that shows a list of vehicles. However, I can't seem to be able to make it work and I'm pretty boggled with this.
The image below displays the table where I need to display the client title using another document. Rest of the values are being pulled from the vehicle's own document.
So far, I had unsuccessful attempts with switchMap and with flatMap (possibly due to lack of experience in using these operators). The only successful attempt was obtaining the client title via a nested observable query from the "vehicles" observable and it performs extremely bad. (Client titles disappear after sorting the table)
This is how I'm fetching the vehicles observable:
this.vehicles$ = this.afs.collection<IVehicle>(`vehicles`);
this.vehicles = this.vehicles$.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as IVehicle;
const $key = a.payload.doc.id;
return { $key, ...data };
});
})
);
This is how I was able to fetch the titles (malfunctions in sort table event - titles disappear for some reason)
this.vehicles = this.vehicles$.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as IVehicle;
const $key = a.payload.doc.id;
const client = data.client;
const clientTitle = this.afs
.doc(`clients/${client}`)
.snapshotChanges()
.pipe(
map(foo => {
const dataFoo = foo.payload.data() as IClient;
let titleString = dataFoo.title;
if (client) {
return { titleString, ...dataFoo };
} else {
titleString = 'N/A';
return { titleString, ...dataFoo };
}
})
);
return { clientTitle, $key, ...data };
});
})
);
I must be doing something wrong while trying to use switchMap, as I can't seem to get the document Id from the vehicle document, even though the vehicle interface includes a "client" field. (see the image below) That's why I didn't complete that snippet to return granular values to append onto the "vehicle" observable.
I just can't seem to catch what am I doing wrong, I would appreciate any direction that shows a "correct" way to approach these types of queries.