0
votes

I'm a novice web developer. I'm currently working on Firebase for a blog project.

This is my DB structure:

enter image description here

On my home page, I'm using this code to get the some latest posts from each of my category

app.get('/test', (req, res) => {

  async function getDocument(db) {
    const ex = await db.collection('Posts').where('category', '==', 'Exercise').orderBy("artID", "asc").limit(4).get();
    const hl = await db.collection('Posts').where('category', '==', 'Health').orderBy("artID", "asc").limit(2).get();
    const fl = await db.collection('Posts').where('category', '==', 'Food & Lifestyle').orderBy("artID", "asc").limit(3).get();
    const md = await db.collection('Posts').where('category', '==', 'Mindfulness').orderBy("artID", "asc").limit(2).get();
    // const author = await db.collection('authors').doc(doc.data().author).get();
    return {
      ex: ex.data(),
      hl: hl.data(),
      fl: fl.data(),
      md: md.data()
    }
  }

  getDocument(db).then(function (data) {
    res.send(data);
  })
})

I've checked the code, and also made sure that the query is indexed in firestore.

But when I execute the function, the browser is throwing an error:

Error: could not handle the request

and I get this error logged in my console.

TypeError: ex.data is not a function
at getDocument (/workspace/index.js:69:14)
at process._tickCallback (internal/process/next_tick.js:68:7)

To get data from Firestore, placing a '.data()' function is needed.

Can somebody help me with where I'm typing the code wrong

2

2 Answers

2
votes

I think the response of await db.collection('Posts').where('category', '==', 'Exercise').orderBy("artID", "asc").limit(4).get(); is a QuerySnapshot - the filter will match more then one value and this is why you cannot access data() because there is more then one object.

You should do something like ex.docs.map(doc => ({ id: doc.id, ...doc.data() }))

0
votes

As per @stefan-prokop-cz mentioned, you need to map each document snapshot from ex.docs. Also, you might wanna consider using Promise.all() to run these queries in parallel to improve computation time.