简体   繁体   中英

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:

在此处输入图片说明

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM