Firebase Firestore函数:未返回任何数据

问题描述 投票:-1回答:1

我已经反复尝试从某个函数从我的Firestore数据库加载数据。但是,firestore从不返回任何数据,并且在'showAll'方法中未记录任何内容。我已经将其缩减为最简单的形式。我要做的就是遍历数据并将其打印到日志中。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.migrate = functions.https.onRequest((req, res) => {
    console.log('running migrate');
    admin.firestore().collection('rooms').get().then(collection => {
      console.log('root collections', collection.docs);
      collection.docs.forEach(doc => {
        console.log('doc in root collection', doc);
      });
   })
   .then(obj => res.send('success'))
   .catch(error => {console.log(error); res.sendStatus(500);});
});

firestore中有数据:picture of data in cloud firestore

我觉得我缺少明显的东西。我还有在触发器上运行的其他功能,它们工作正常。这是我未在文档引用中传递的唯一函数,并且是唯一未获取数据的函数。

我还应该使用其他路径来查找数据吗?我是否缺少初始化片段? (我正在firebase服务器上运行此程序,因为我可以使其在本地运行的唯一方法是在代码中包含一个服务帐户,而我不想这样做)。除“ admin.firestore()”外,我是否还应使用其他方式进入我的Firestore?

感谢您的帮助!

javascript firebase google-cloud-firestore google-cloud-functions
1个回答
0
投票

仅在所有异步工作完成后,才需要将响应发送给客户端。现在,您将立即发送响应,而无需等待查询完成。当您从HTTP类型的函数返回响应时,即使没有完成,Cloud Functions也会终止并清理所有异步工作。

您的函数的最低版本将如下所示:

exports.migrate = functions.https.onRequest((req, res) => {
    console.log('running migrate');
    admin.firestore().collection('rooms').get()
    .then(collection => {
        collection.docs.forEach(doc => {
            console.log('doc in root collection', doc);
        });
        res.send('success');
    })
    .catch(error => console.log(error));
});

请注意,查询完成后,在回调内部将调用res.send

如果您要将查询移至另一个函数,则该函数将必须返回一个Promise,并且调用方将不得不等待它以在适当的时间发送响应。

简而言之,请务必完全理解promise的工作方式,否则您的功能可能会以神秘的方式失败。

© www.soinside.com 2019 - 2024. All rights reserved.