javascript - 尝试通过云功能连接到 Firestore 时,为什么会出现“预期的 catch() 或返回”错误?
问题描述
我使用带有一定数量集合的 google cloud firestore。我正在尝试编写一个谷歌云函数,该函数根据 http 请求返回此 Firestore 中的集合数。
所以我从这个问题写了以下index.js
文件绘图:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.queryForData = functions.https.onRequest((request, response) => {
var db = admin.firestore();
db.get().then(snap => {
response.status(200).send({length: snap.size});
})
});
部署后,我收到此错误:
奇怪的是:当我删除行 var 时db = admin.firestore();
,我得到了同样的错误。所以我怀疑,我根本没有正确连接到 Firestore。
我究竟做错了什么?
解决方案
正如HTTP Cloud Function的官方视频catch()
所述,您应该在 Cloud Function 中添加一个块,如下所示:
exports.queryForData = functions.https.onRequest((request, response) => {
var db = admin.firestore();
db.get()
.then(snap => {
response.status(200).send({length: snap.size});
//Or response.send({length: snap.size});
})
.catch(error => {
console.log(error);
response.status(500).send(error);
})
});
但是,此外,如果我没记错的话,您的 Cloud Function 中存在(另一个)错误:您这样做了,但Firestore 服务接口db.get()
没有get()
方法。您应该调用a 上的方法,因为您正在使用返回的方法(即):get()
CollectionReference
size()
QuerySnapshot
snap
exports.queryForData = functions.https.onRequest((request, response) => {
var db = admin.firestore();
db.collection('collectionId').get()
.then(snap => {
response.status(200).send({length: snap.size});
//Or response.send({length: snap.size});
})
.catch(error => {
console.log(error);
response.status(500).send(error);
})
});
请注意,您也可以调用get()
.DocumentReference
推荐阅读
- sql-server - nodejs mssql影响行在插入时总是没有
- linux - 如何在 Unix / Mac 上定位并直接连接到以太网卡
- python-3.x - 相当于 R 在 Python 中“附加”数据框?
- python - BS4:解析 HTML,存储解析的元素并仅在网页上发布新信息时作为文本发送
- java - 在android 3.1及更高版本中获取连接的蓝牙低功耗设备列表
- java - Jenkins 无法克隆 Git 存储库
- c# - ASP.NET Core IHostedService 手动启动/停止/暂停(?)
- c# - Visual Studio 无法加载文件或程序集、metroframework、Version=1.4.0.0、Culture=neutral
- c# - 使用 C# 中的本地翻译文本创建(默认)按钮
- python - 您将如何从字典中删除随机键,但前提是该项目具有特定值?