0

I would just like to access my Firestore Database from within my Firebase Functions. I have tried to follow all the documentation and other stack overflow questions but still it is not working. Here is my code:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.test = functions.https.onRequest((request, response) => {
  admin
    .firestore()
    .collection('users')
    .get()
    .then(querySnapshot => {
      const arrUsers = querySnapshot.map(element => element.data());
      return response.send(arrUsers);
    }).catch((error) => {
      // It is coming in here, and this below just returns '{}'
      response.send(error);
    });
});

What am I doing wrong?

1 Answer 1

4

The get() method of a CollectionReference returns a QuerySnapshot which "contains zero or more DocumentSnapshot objects representing the results of a query. The documents can be accessed as an array via the docs property or enumerated using the forEach() method".

Therefore you should do as follows, calling map() on querySnapshot.docs:

exports.test = functions.https.onRequest((request, response) => {
  admin
    .firestore()
    .collection('users')
    .get()
    .then(querySnapshot => {
      const arrUsers = querySnapshot.docs.map(element => element.data());
      //return response.send(arrUsers);  //You don't need to use return for an HTTPS Cloud Function
      response.send(arrUsers);   //Just use response.send()
    }).catch(error => {
      //response.send(error);
      response.status(500).send(error)   //use status(500) here
    });
});

Note the changes to the code for returning the response and handling the error. I would suggest that you watch this official Firebase video on HTTPS Cloud Functions: https://www.youtube.com/watch?v=7IkUgCLr5oA, it's a must!

Sign up to request clarification or add additional context in comments.

3 Comments

I highly recommend this documentation when working with cloud functions. Great examples: googleapis.dev/nodejs/firestore/latest/index.html
Good answer! On querySnapshot.docs.map(... I keep making this mistake myself, since QuerySnapshot does implement forEach(), but does not implement map().
Thank you very much! I think the important thing I missed was the querySnapshot.DOCS part. Also thank you for the extra links to learn some more! Stuff like this is always useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.