【问题标题】:How do I return each collection and its documents in firestore with cloud functions?如何使用云功能在 Firestore 中返回每个集合及其文档?
【发布时间】:2020-10-29 15:59:24
【问题描述】:

想要返回一个包含 [1year, 1month, etc] 的数组,每个数组都是包含每个文档的数组。

目前,这会返回一个空数组,但是当我打印快照的大小时,我会得到正确的值。不确定我是否正确使用了 push() 或者这是一个异步问题。谢谢。

exports.getStockPrices = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    const currentUser = {
      token: req.headers.authorization.split('Bearer ')[1]
    };
    // ! this is a post request
    admin
      .auth()
      .verifyIdToken(currentUser.token)
      .then(decodedToken => {
        // keep this just in case we want to add anything to do with the user
        const user = decodedToken;
        // array of collections e.g [1year, 1mo, etc]
        const data = [];
        // array of documents e.g [18948901, 1984010471, etc]
        const documents = [];
        db.collection('historical')
          .doc(`${req.body.ticker}`)
          .listCollections()
          .then(collections => {
            // each collection is the 1year, 1mo, etc
            collections.forEach(collection => {
              collection.get().then(querySnapshot => {
                console.log('number of documents: ' + querySnapshot.size);
                querySnapshot.forEach(doc => {
                  // doc.data is each piece of stock data
                  documents.push(doc.data());
                });
                // each document e.g 1year, 1mo, etc
                data.push(documents);
              });
            });
            return data;
          })
          .then(data => {
            return res.json({ data });
          })
          .catch(err => {
            console.log(err);
            return res.status(500).send({ error: 'error in getting data' });
          });
      })
      .catch(err => {
        console.log(err);
        return res.status(500).send({
          error: 'error authenticating user, please try logging in again'
        });
      });
  });
});

【问题讨论】:

  • 您没有正确使用 Promise。在发送最终响应之前,您必须等到所有承诺解决后。您正在发送一个空数组,因为响应是在数组填充之前发送的。如果您添加更多控制台日志记录以查看事情发生的顺序,您将看到这一点。
  • @DougStevenson 所有的承诺在哪里?我虽然我的最终 .then() 等待他们,然后发送最终响应。谢谢
  • 每个then 都会立即返回并承诺。它实际上并没有阻止代码。如果您添加更多调试日志记录,您会更好地看到正在发生的事情。您将不得不更详细地了解 Promise 的工作原理。

标签: javascript node.js firebase google-cloud-firestore


【解决方案1】:

由于异步调用的性质,您的返回发生在您的数组被填充之前。

你可以试试我的例子,我的firebase函数被定义为async这允许我使用await,这个语句允许通过等待promise来为你的firestore操作添加一种同步。

const functions = require('firebase-functions');
const admin = require('firebase-admin');


admin.initializeApp();
const db = admin.firestore();

exports.eaxmple =  functions.https.onRequest(async (req, res) => {
    var datax = []

    var collections = await db.collection('collection').doc('docid').listCollections()
    for (collection in collections) {
            content =  await collections[collection].get().then(querySnapshot => {
            console.log('number of documents: ' + querySnapshot.size);
            return querySnapshot.docs.map(doc => doc.data());

        });
        datax.push(content)

    }
    return res.json({datax});


});

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2020-04-04
    • 2018-05-19
    • 2021-02-13
    • 2019-08-07
    • 2021-08-12
    • 1970-01-01
    • 2019-06-02
    • 2020-01-24
    相关资源
    最近更新 更多