Home > Back-end >  Build Firebase queries dynamically
Build Firebase queries dynamically

Time:11-06

I'm wondering if it's possible to build firebase queries dynamically, at the moment I'm using a variable to determine if startAfter should be included or not.

As you can see this is causing duplicate code, for just one variable

export async function fetchUserPhotosPaginated(userId: string, lastUserPhoto?: QueryDocumentSnapshot): Promise<QuerySnapshot> {
    if (lastUserPhoto) {
        return await getDocs(query(
            collection(db, 'photos'),
            orderBy('createdAt', 'desc'),
            startAfter(lastUserPhoto),
            where('user.id', '==', userId),
            limit(5)
        ))
    }

    return await getDocs(query(
        collection(db, 'photos'),
        orderBy('createdAt', 'desc'),
        where('user.id', '==', userId),
        limit(5)
    ))
}

I've tried

  • Use startAfter(null), this did not give the intended effect
  • assign the query to a variable let q = query(...) to then update that query using q = q.startAfter(...) this also did not work

CodePudding user response:

The second method of adding startAfter conditionally is correct but your syntax to update query is not. Try refactoring the function as shown below:

export async function fetchUserPhotosPaginated(userId: string, lastUserPhoto?: QueryDocumentSnapshot): Promise<QuerySnapshot> {
  // Initial query
  let q = query(collection(db, 'posts'), orderBy('createdAt', 'desc'))
  
  // Add startAfter is lastUserPhoto is present    
  if (lastUserPhoto) q = query(q, startAfter(lastUserPhoto));
  
  // Add remaining conditions
  q = query(q, where('user.id', '==', userId), limit(5)); 

  return await getDocs(q)
}

You can also add all conditions in an array as explained in following answer:

Firestore conditional where clause using Modular SDK v9

  • Related