Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
Build Firebase queries dynamically

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
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda