Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!