skip to Main Content

My database picture
I’m trying to get a field inside document by using query method. But I can’t and I’m not getting any error ("probably query response is empty")

const chatId = "6042ff11-fe94-4e65-958b-80130d9e7108"

 const docRef = collection(db, 'userGroups');
      const q = query(docRef, where(`${chatId}`, "==", `${chatId}`));
      // I also tried method below but I got no result
      // const q = query(docRef, where(`${chatId}`, "==", `${chatId}`));
      const gg = (await getDocs(q))
      gg.forEach(doc => {
        console.log(doc);
      });

2

Answers


  1. You are querying for a field name that has the same data as the name. Given your screenshot, this would always come back empty.

    const q = query(docRef, where("6042ff11-fe94-4e65-958b-80130d9e7108", "==", "6042ff11-fe94-4e65-958b-80130d9e7108"));
    

    In your database, the value in the "6042ff11-fe94-4e65-958b-80130d9e7108" field looks like it has some JSON. Do you see why this would never return anything? You don’t have any data where the key "6042ff11-fe94-4e65-958b-80130d9e7108" also has the data "6042ff11-fe94-4e65-958b-80130d9e7108".

    Try a not-equals operator, since the value of the chat ID will probably never equal the chat ID:

    const q = query(docRef, where(chatId, '!=', chatId), select(chatId));
    
    Login or Signup to reply.
  2. As @dzylich also answered, your query won’t return any results because there is no document that matches this condition:

    const q = query(docRef, where(`${chatId}`, "==", `${chatId}`));
    

    If you want to just get the document(s) where the chatId field exists, you could use a != condition with a "known to not exist" value:

    const q = query(docRef, where(chatId, "!=", "This value does not exist"));
    

    This query matches all documents that have a chatId field, with any value (except the actual value passed). It will not match documents without that field, as those documents won’t exist in the index it uses for the lookup.


    Note that this is a bit of an antipattern, so if you still can, I’d recommend adding a field chatId to the document with the value, so that you can do the much simpler query:

     const q = query(docRef, where("chatId", "==", chatId));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search