Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda