【问题标题】:How do I query Firestore all documents today date?如何查询 Firestore 今天所有文档的日期?
【发布时间】:2019-12-12 09:01:22
【问题描述】:

我正在尝试按固定时间表生成报告。但是我遇到了一个问题,在该函数将运行的当前时间之前,我无法检索从今天开始的日期。

exports.generateReport = functions.pubsub.schedule('36 15 * * *').onRun(async (context) => {
    console.log(context);
    const currentTime = admin.firestore.Timestamp.now();

    const shopSnapshot = await db.collection("shops").get();
    let shopDoc = shopSnapshot.docs.map(doc => doc.data());

    const promises = [];
    let transactionList = [];
    let reportList = [];

    let i = 0;

    console.log(shopDoc);

    shopDoc = shopDoc.filter(shop => !!shop.key);
    console.log(shopDoc);

    for(var j=0; j<shopDoc.length; j++){
        console.log("Enter shop ID:"+shopDoc[j].key);
        promises.push(db.collection("shops").doc(shopDoc[j].key).collection("transactions").get());
    }  

    const snapshotArrays = await Promise.all(promises);

    snapshotArrays.forEach(snapArray => {
        snapArray.forEach(snap => {
            //console.log(snap.data());
            transactionList.push({data: snap.data(), key: shopDoc[i].key});
        })
        i++;
    }); 

    for(var k=0; k<shopDoc.length; k++){
        let amount = 0;
        for (var l=0; l<transactionList.length; l++){
            if(shopDoc[k].key === transactionList[l].key){
                console.log("get date");

                if (transactionList[l].data.createAt < currentTime){
                    amount += transactionList[l].data.amount;
                    console.log(amount);
                }
            }
        }
        reportList.push({amount: amount, key: shopDoc[k].key});
    }

    console.log(reportList);
    console.log(transactionList);

});

我尝试使用new Date() 也与一串与 Firestore 时间戳格式完全相同的日期字符串进行比较,但所有交易仍然出现在该时间之前或此时不包含任何交易。

【问题讨论】:

  • 出于测试目的,这就是我输入functions.pubsub.schedule('36 15 * * *')的原因。我想检查所有交易文件 createAt 是否是今天的日期。那我只取今天日期的所有交易文件
  • 好的,谢谢你的回答(我同时删除了我的评论......因为我看到你在做transactionList[l].data.createAt &lt; currentTime
  • 如果我正确理解您的业务需求,您想以某种方式在明天 00:01 运行 Cloud Function 并选择今天的所有交易,这样您就可以生成包含所有交易的报告前一天。对吗?
  • 是的,我想获取从今天到当前时间的日期
  • 是的,没错

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


【解决方案1】:

如果我正确理解您希望通过在今天 00:05 运行计划 Cloud Function 来为昨天发生的所有事务生成每日报告,那么这是使用 moment.js 库的可能方法:

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

const moment = require('moment');

admin.initializeApp();


exports.generateReport = functions.pubsub.schedule('05 00 * * *').onRun(async (context) => {

    let m1 = moment();
    let m2 = moment();
    m1.add(-1, 'days');
    m2.add(-1, 'days');
    m1.startOf('day');
    m2.endOf('day');


    const shopSnapshot = await db.collection("shops").get();
    let shopDoc = shopSnapshot.docs.map(doc => doc.data());

    const promises = [];
    let transactionList = [];
    let reportList = [];

    let i = 0;

    shopDoc = shopDoc.filter(shop => !!shop.key);
    console.log(shopDoc);

    for(var j=0; j<shopDoc.length; j++){
        console.log("Enter shop ID:"+shopDoc[j].key);
        promises.push(
          db.collection("shops")
            .doc(shopDoc[j].key)
            .collection("transactions")
            .orderBy("createAt")
            .where("createAt", ">", m1.toDate())
            .where("createAt", "<=", m2.toDate())
            .get()
       );
    }  

    const snapshotArrays = await Promise.all(promises);

    snapshotArrays.forEach(snapArray => {
        snapArray.forEach(snap => {
            //console.log(snap.data());
            transactionList.push({data: snap.data(), key: shopDoc[i].key});
        })
        i++;
    }); 

    for(var k=0; k<shopDoc.length; k++){
        let amount = 0;
        for (var l=0; l<transactionList.length; l++){
            if(shopDoc[k].key === transactionList[l].key){
                 amount += transactionList[l].data.amount;
            }
        }
        reportList.push({amount: amount, key: shopDoc[k].key});
    }

    //.....

});

那么,我们在这段代码中做了什么? 首先,我们创建两个时刻对象,并将它们的日期设置为昨天。然后,使用startOf()endOf(),我们将第一个的时间调整为昨天上午 12:00:00.000(即 00:00:00,请参阅here),第二个调整为昨天的 11:59 :59.999 pm(即 23:59:59)。

对于这两个日期,对于每个交易集合,我们将query 改编如下,调用toDate() 方法:

db.collection("shops")
                .doc(shopDoc[j].key)
                .collection("transactions")
                .orderBy("createAt")
                .where("createAt", ">", m1.toDate())
                .where("createAt", "<=", m2.toDate())
                .get();

就是这样。这里最大的优势是过滤是在 Firestore 数据库中完成的(在后端),而不是像您在问题中所做的那样在前端(if (transactionList[l].data.createAt &lt; currentTime){...}

【讨论】:

  • 不知道为什么当我使用orderByChild 时出现错误,它不是函数。但是当我使用orderBy 时它工作正常。感谢您的详细解释
  • 很高兴能帮到你!是的,orderBy 有一个错字,因为我改编了我为实时数据库制作的代码之一。很好,你抓住了它!
猜你喜欢
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
相关资源
最近更新 更多