darkhorse
darkhorse

Reputation: 8782

Can't read data from Firestore using my Firebase function

I wrote a simple function to learn how to read data from my firestore. The index.js file looks like this:

const functions = require('firebase-functions');

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

const express = require('express');
const cors = require('cors');
const app = express();

// Automatically allow cross-origin requests
app.use(cors({ origin: true }));

// GET
app.get('/', (request, response) => {
    var db = admin.firestore();
    db.collection('users').doc('vUuMvkP03J2hMryAm9ok').get().then(snapshot => {
        response.send(snapshot.username);
    }).catch(reason => {
        response.send(reason);
    });
});

exports.myFunction = functions.https.onRequest(app);

In the GET request, I'm trying to read the document stored under users collection, and send back the username field. My database looks like this:

enter image description here

When I go to my function's URL, I get an empty page with nothing on it. No sensible errors either. What exactly am I doing wrong?

Upvotes: 1

Views: 814

Answers (1)

Dylan
Dylan

Reputation: 1714

The firestore response's data is in snapshot.data() If you add that to your callback, you should be good

response.send(snapshot.data().username);  

There are other properties on the snapshot like snapshot.id which would give you vUuMvkP03J2hMryAm9ok in your example.

Upvotes: 2

Related Questions