skip to Main Content

Can someone explain to me why I am not able to perform a simple Firebase query checking for a specific timestamp in a subcollection?
The code below works if I try to retrieve the whole document, but if I add the where query it just returns a 200 response with an empty body.
I have also tried to replace db.collection with db.collectionGroup and in this case I get a 500 response with the following message Collection IDs must not contain '/'.

Here you can see how I have structured my data and my code:

enter image description here

try {
     const reference = db.collection(`/data/10546781/history`).where("timestamp", "==", 1659559179735)
        
     const document = await reference.get()
        
     res.status(200).json(document.forEach(doc => {
         doc.data()
         console.log(doc.data())
     }))
        
} catch(error) {
    res.status(500).json(error)
    console.log(error)
};

2

Answers


  1. Chosen as BEST ANSWER

    @Dharmaraj Thanks for the help. Your answer was part of the solution. The other part concerned how my data was structured. The timestamp needed to be at the parent level of the subcollection document. So either outside the realTimeData object or the whole object needs to be flattened at the parent level.

    enter image description here


  2. It seems you are looking for map() that creates a new array and not forEach() loop that returns nothing. Try:

    const reference = db.collection(`/data/10546781/history`).where("realtimeData.timestamp", "==", 1659559179735)        
    
    const snapshot = await reference.get()
    
    const data = snapshot.docs.map((d) => ({
      id: d.id,
      ...d.data()
    }))
    
    res.status(200).json(data)
    

    Additionally, you need to use the dot notation if you want to query based on a nested field.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search