首页 > 解决方案 > 尝试通过云功能连接到 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。

我究竟做错了什么?

标签: javascriptnode.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


正如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()CollectionReferencesize()QuerySnapshotsnap

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


推荐阅读