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

165
Visualizações
react Firestore query nested collection where field then update, or add new doc

I'm currently ripping my hair out trying to query a nested collection in my Firestore db.

my db is set up as follows:

  users (collection)
    - username
    - displayName
    - ratedItems (collection)
            - itemId
            - timestamp
            - likedItem

I want to be able to add/update the rated item in the ratedItems collection for a specific user but I seem to be hitting 2 problems:

  1. I assume the query is incorrect as if(querySnapshot.empty) always returns false even if there are no matching items (matching the itemId) in the ratedItems collection, so it always attempts to add a new item which results in duplicate entries in the collection.

  2. if I force the code to bypass the conditional it throws an error when it attempts to update the existing item:

Expected type 'mc', but it was: a custom yc object

My thoughts are I am using the collectionGroup query incorrectly but I haven't found a solution for this yet. Should I even be using collectionGroup at all?? from what I've read, if I understand correctly this will query every ratedItem collection regardless of the user, which isn't what I want

 const rateItem = async (itemId, liked) => {
    try {
      const itemRef = collection(db, 'users', currentUser.uid, 'ratedItems');
      const q = query(
        collectionGroup(db, 'users', currentUser.uid),
        where('itemId', '==', itemId)
      );
      const querySnapshot = await getDocs(q);

      if (querySnapshot.empty) {
        await addDoc(itemRef, {
          itemId: itemId,
          timestamp: serverTimestamp(),
          likedItem: liked,
        });
      } else {
        await updateDoc(itemRef, {
          timestamp: serverTimestamp(),
          likedItem: liked,
        });
      }
    } catch (err) {
      console.log(err.message);
    }
  };
about 4 years ago · Juan Pablo Isaza
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