1
votes

I'm trying to do a simple firestore query, using a where clause inside firebase cloud functions but I get foo.data is not a function.

exports.uploadList = functions.https.onRequest(async (req, res) => {
 try {
    let foo = await db.collection('users').where('appToken', '==', 'xxxx').get()
    if (foo) {
      return res.status(200).send({ foo: foo.data() })
    }
  } catch (error) {
    return res.status(500).send(error)
  }
})

The response I get is an empty object {}, if I remove the try/catch block I can see an error in cloud functions log foo.data is not a function.

I read that where() is optional so also tried db.collection('users').get(), same result.

I can query using db.collection().doc().get() and it works fine but no way to find a document by a field value. set and update also work fine.

1

1 Answers

3
votes

This bit of code you've written:

db.collection('users').where('appToken', '==', 'xxxx').get()

returns a promise that resolves with a QuerySnapshot type object (not a DocumentSnapshot). As you can see from linked API documentation, QuerySnapshot doesn't have a data() method like DocumentSnapshot does. That's because the SDK doesn't know how many documents are in the result set ahead of time. So, you'll have to iterate the results. One way to do that is with the docs property on QuerySnapshot, which is just an array of QueryDocumentSnapshots that match the query constraints. Or use its forEach method.

There are plenty of examples in the documentation.