未获取集合Firebase函数中的所有文档

sigwle7e  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(133)

我试图获取集合中的所有文档,.forEach文档对子集合进行查询,并从中获取最新(按日期)文档,但由于某种原因,查询大小始终为0
下面是代码:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

/// Updates the last payment done in the neighbors documents
export const updateLastPaymentHTTP = functions.https.onRequest(
  async (request, response) => {
    try {
      const neighbors = await admin.firestore()
                                   .collection("neighbors").get();
      const promises = [];
      neighbors.forEach(async (neighbor) => {
        const topPaymentRef = admin.firestore()
                                   .collection(`neighbors/${neighbor.ref}/payments`)
                                   .orderBy("date", "desc")
                                   .limit(1)
                                   .get();
        const querySize = await topPaymentRef.then((query) => query.size);
        console.log(`Query Size: ${querySize}`);
        if (querySize === 1) {
          const lastPayment = (await topPaymentRef).docs[0].data();
          promises.push(neighbor.ref.update({ last_payment: lastPayment }));
        } else {
          promises.push(neighbor.ref.update({ last_payment: "" }));
        }
      });
      await Promise.all(promises);
      response.send("Update Last Payments Completed");
    } catch (error) {
      console.log(`Error Updating Last Payment ${error}`);
    }
  }
);

我做查询检查是因为在一些邻居文档中没有一个名为payments的子集合,但在大多数邻居文档中有:
With Payments
和/或
Without Payments
但是我的querySize === 1总是false,我更新了{ last_payment: '' }。我也尝试了解释here的每个选项,我的集合查询有什么问题吗?

jgwigjjp

jgwigjjp1#

代码中有几个地方需要调整:

以下内容应该有效(未经测试):

export const updateLastPaymentHTTP = functions.https.onRequest(
    async (request, response) => {
        try {

            const db = admin.firestore();

            const neighbors = await db.collection("neighbors").get();

            const neighborsRefs = [];
            let promises = [];

            neighbors.forEach((neighbor) => {

                promises.push(db.collection(`neighbors/${neighbor.ref}/payments`)
                    .orderBy("date", "desc")
                    .limit(1)
                    .get());

                neighborsRefs.push(neighbor.ref);

            });

            const paymentsQuerySnapshotsArray = await Promise.all(promises);

            promises = [];
            paymentsQuerySnapshotsArray.forEach((paymentsQuerySnapshot, idx) => {

                if (paymentsQuerySnapshot.size === 1) {
                    const lastPayment = paymentsQuerySnapshot.docs[0].data();
                    promises.push(neighborsRefs[idx].update({ last_payment: lastPayment }));
                } else {
                    promises.push(neighborsRefs[idx].update({ last_payment: "" }));
                }

            })

            await Promise.all(promises);
            response.status(200).send("Update Last Payments Completed");
        } catch (error) {
            console.log(`Error Updating Last Payment ${error}`);
            response.status(500).send(error.message);
        }
    }
);
iszxjhcz

iszxjhcz2#

跟进Renaud代码和Doug解决方案,我发现问题与neighbor.ref有关,我将其更改为neighbor.ref.id,然后一切正常,以下是我在Renaud代码中的更改:
首先,我添加了一个常量,以便保存每个邻居的id并将它们添加到列表中:

neighbors.forEach((neighbor) => {
    const neighborId = neighbor.ref.id;  /// Here
    promises.push(
      db
        .collection(`neighbors/${neighborId}/payments`)
        .orderBy("date", "desc")
        .limit(1)
        .get()
    );

    neighborsRefsId.push(neighborId);  /// And Here
  });

然后,在获得所有邻居的promise之后,我创建了一个名为refDoc的变量,以保存每个查询的所有引用,并相应地更新文档。

const paymentsQuerySnapshotsArray = await Promise.all(promises);

      promises = [];
      paymentsQuerySnapshotsArray.forEach((paymentsQuerySnapshot, idx) => {
        const refDoc = db.doc(`/neighbors/${neighborsRefsId[idx]}`);
        if (paymentsQuerySnapshot.size === 1) {
          const lastPayment = paymentsQuerySnapshot.docs[0].data();
          promises.push(refDoc.update({ last_payment: lastPayment }));
        } else {
          promises.push(refDoc.update({ last_payment: "" }));
        }
      });

希望这对其他人有帮助。

相关问题