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

Dan*_*evi 9 javascript node.js firebase google-cloud-platform google-cloud-firestore

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

就像是 :

firestore.collection("purchases").where("ErrorID", "==", "0").get(Order, Amount); 
Run Code Online (Sandbox Code Playgroud)

我正在谈论的功能:

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,
    });
  }
};
Run Code Online (Sandbox Code Playgroud)

我正在谈论的文件

我正在谈论的文件

Dha*_*raj 14

如果您使用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();
Run Code Online (Sandbox Code Playgroud)

  • @Peter 1 个文档 = 1 读。选择在这里没有影响。 (2认同)