首页 > 解决方案 > Firebase 函数/firestore 不起作用并捕获返回空对象

问题描述

我只想从我的 Firebase 函数中访问我的 Firestore 数据库。我已尝试关注所有文档和其他堆栈溢出问题,但仍然无法正常工作。这是我的代码:

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);
    });
});

我究竟做错了什么?

标签: firebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


a的get()方法CollectionReference返回 a QuerySnapshot“包含零个或多个DocumentSnapshot表示查询结果的对象。文档可以通过docs属性作为数组访问或使用该方法枚举forEach()”。

因此,您应该执行以下操作,map()调用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
    });
});

请注意用于返回响应和处理错误的代码的更改。我建议您观看有关 HTTPS Cloud Functions 的 Firebase 官方视频:https ://www.youtube.com/watch?v=7IkUgCLr5oA ,这是必须的!


推荐阅读