I'm currently developing an admin dashboard using Firebase, where I need to fetch data for all members, including their related payments and vehicles.
Here is the data model I'm working with - overview of data schema using Typescript types
export type VehicleDocType = {
// Vehicle document fields
owner: string; // Member id
...
};
export type PaymentDocType = {
// Payment document fields
recipient: string; // Member id
...
};
export type MemberDocType = {
uid: string;
...
/* Note! Arrays are not coming from Firestore and not even part of Schema.
it is used to map relations on the client side
*/
payments: Array<PaymentDocType> | null;
vehicles: Array<VehicleDocType> | null;
};
Data structure in Firebase:
----------------------------------------------------------
| Collections | Documents | Fields |
----------------------------------------------------------
| members | n docs | { uid: doc.id, ...} |
| payments | n docs | { recipient: member.id, ... } |
| vehicles | n docs | { owner: member.id, ... } |
----------------------------------------------------------
Note: vehicles
collection is the same as payments
.
For the member page, I want to display all members along with their associated payments and vehicles.
This is my current approach for fetching data:
Firebase SDK: "firebase": "^9.22.0"
Exact queries I want to run:
const fetchCustomers = async () => {
// Fetch member documents from the 'membersCol' collection
const memberDocs = (await getDocs(membersCol)).docs.map((d) => d.data());
// Fetch payment documents from the 'paymentsCol' collection
const paymentDocs = (await getDocs(paymentsCol)).docs.map((d) => d.data());
// Fetch vehicle documents from the 'vehiclesCol' collection
const vehicleDocs = (await getDocs(vehiclesCol)).docs.map((d) => d.data());
const members = memberDocs.map((member) => ({
...member,
payments: paymentDocs.filter((p) => p.recipient === member.uid),
vehicles: vehicleDocs.filter((v) => v.owner === member.uid),
}));
// Further processing and rendering of the data
};
While this approach is functional, I have encountered a few problems:
- Loading large datasets can result in slow data retrieval times.
- When implementing Firebase pagination queries, I'm unsure how to efficiently map the relations (vehicles and payments) to each member.
- I'm looking for best practices to fetch the data with minimal document reads and optimize the overall loading time.
Any suggestions or recommendations on how to improve the data fetching process, optimize document reads, and reduce loading time would be greatly appreciated. Furthermore, if someone have any recommendations on how to implement real-time updates in this situation.