Ad

Is There A Way To Query Firebase Fields?

I am working on a performance issue of a function, that takes 15sec to response, which makes a request to firebase for all documents that are "ErrorID" "==" "0" The problem is that there are many documents and they are kind of very large objects, and I only need TWO FIELDS(Order and Amount) of each document, there are any way to request only those two fields that accomplish the condition?

Something like :

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

The function that im talking about:

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

The document im talking about

Ad

Answer

You might have to use Firestore Node.JS client, then you can use select() to select fields:

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

const firestore = new Firestore();

const snap = firestore
  .collection("purchases")
  .where("ErrorID", "==", "0")
  .select("Order", "Amount")
  .get();
Ad
source: stackoverflow.com
Ad