Lia189
Lia189

Reputation: 41

Unable to perform a Firebase query on a timestamp and receiving an empty body in response

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)
};

Upvotes: 0

Views: 65

Answers (2)

Dharmaraj
Dharmaraj

Reputation: 50830

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.

Upvotes: 1

Lia189
Lia189

Reputation: 41

@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

Upvotes: 0

Related Questions