firebase - 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);
});
});
我究竟做错了什么?
解决方案
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 ,这是必须的!
推荐阅读
- ionic3 - Ionic 3 - 播放从网站下载并存储在设备数据目录中的视频
- ios - cordova-sqlite-storage 插件与原生 iOS 框架的 sqlite 数据库冲突
- mysql - 具有相同 ID 但值不同的两行上的 CASE
- java - 带有 Spring boot jpa 错误的 SQL 服务器过程调用:“无法提取 OUT/INOUT 参数值”
- c# - EF多对多关系添加数据
- module - ZF3 多模块中的控制器名称和别名相同
- git - 从本地 git 文件夹同步到远程文件夹
- reactjs - React 路由器未从 public/index.html 加载脚本
- python-3.x - 创建数据框,其中每一行由另一个数据框的列名和值组成
- java - 如何在主java中调用函数Keypress