有没有办法从 Firestore 中仅选择某些字段?

2023-11-23

我正在解决一个函数的性能问题,需要 15 秒才能响应,这会向 firebase 请求所有文档"ErrorID" "==" "0"问题是有很多文档,而且它们是非常大的对象,我只需要两个领域 (Order and Amount)对于每个文档,有什么方法可以只请求满足条件的那两个字段?

就像是 :

firestore.collection("purchases").where("ErrorID", "==", "0").get(Order, Amount); 

我正在谈论的功能:

const totalEarn = async (req, res, next) => {
  const DAY = 86400000;
  const WEEK = 604800016;
  const MONTH = 2629800000;

  try {
    let snap = await firestore.collection("purchases").where("ErrorID", "==", "0").get(); // CONDITION
    let totalToday = 0;
    let totalYesterday = 0;
    let totalLastWeek = 0;
    let totalLastMonth = 0;
    let now = Date.now();
    let Yesterday = now - 86400000;

    await snap.forEach((doc) => { // THIS FOR EACH TAKES TOO MUCH TIME
      let info = doc.data();
      let time = info.Order.split("-")[2]; // FIRESTORE FIELD -> ORDER
      let amount = info.AmountEur * 1; // FIRESTORE FIELD -> AMOUNT

      if (time > now - DAY) {
        totalToday = totalToday + amount;
      }
      if (time < now - DAY && time > Yesterday - DAY) {
        totalYesterday = totalYesterday + amount;
      }
      if (time > now - WEEK) {
        totalLastWeek = totalLastWeek + amount;
      }
      if (time > now - MONTH) {
        totalLastMonth = totalLastMonth + amount;
      }
    });

    res.send({
      status: true,
      data: {
        totalToday: totalToday.toFixed(2),
        totalYesterday: totalYesterday.toFixed(2),
        totalLastWeek: totalLastWeek.toFixed(2),
        totalLastMonth: totalLastMonth.toFixed(2),
      },
    });
  } catch (error) {
    res.status(410).send({
      status: false,
      error: "some error occured counting the numbers",
      e: error.message,
    });
  }
};

我正在谈论的文件

The document im talking about


如果你使用Firestore Node.JS 客户端或 Firebase Admin SDK,然后您可以使用select()选择字段:

import { Firestore } from "@google-cloud/firestore";

const firestore = new Firestore();

const snap = firestore
  .collection("purchases")
  .where("ErrorID", "==", "0")
  .select("Order", "Amount")
  .get();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法从 Firestore 中仅选择某些字段? 的相关文章

随机推荐