Home > Software design >  Firebase: Collection group query and then get parent of sub collection
Firebase: Collection group query and then get parent of sub collection

Time:07-23

My data model:

A Trip has a sub collection Rides and references the trip with tripId

A ride has an experience: string which I'd like to filter on.

So I thought to query the SubCollection Rides

export const getTripsByExperience = async (experience: EXPERIENCES) => {
  const ridesQuery = query(
    collectionGroup(db, 'rides'),
    where('experience', '==', experience)
  );
  const querySnapshot = await getDocs(ridesQuery);
  let trips: Trip[] = [];
  querySnapshot.forEach(async (rideDoc) => {
    const ride = rideDoc.data();
    const tripSnapshot = await getDoc(doc(db, 'trips', ride.id));
    trips.push({ ...tripSnapshot.data(), id: tripSnapshot.id });
  });
  return trips
}

When I console.log this out right after trips.push trips.length gets incrementally bigger, but when the loop finishes, the function returns an empty array

  • Related