Reputation: 2441
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?
Upvotes: 0
Views: 576
Reputation: 83163
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!
Upvotes: 4