【问题标题】:Firestore Cloud Function query by DATE按 DATE 的 Firestore Cloud Function 查询
【发布时间】:2020-05-28 15:30:38
【问题描述】:

我正在尝试向 Firestore 数据库查询集合并按日期过滤。 我有一个时间戳字段,当名为“specificDate”的字段等于 now() 时,我需要获取结果。

app.get('/execute',  async(req, res, next) => {

  const snaps = await db.collection('notifications').where("specificDate", "==", new Date()).get()

  const results= [];
  snaps.forEach(snap => results.push(snap.data()));
  res.status(200).json({results});
});

无论任何组合,我都没有结果。如果我将“==”更改为“”,我就有结果。 我担心这个问题与时间有关,我想忽略它,我只关心年、月和日。 下图说明了我的 Firestore 收藏,只有一件 1 件。

我一直在研究,但我还不走运。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    使用 AND 查询为查询提供所需的范围。由于您不关心精确匹配时间,所以给它整个天范围。

    var start = new Date();
    start.setHours(0,0,0,0);
    
    var end = new Date(start.getTime());
    end.setHours(23,59,59,999);
    
    const snaps = await db.collection('notifications').where("specificDate", ">=", start ).where("specificDate", "<=", end).get()
    

    【讨论】:

      【解决方案2】:

      使用 Firestore Timestamp 的 fromDate() 方法构建查询应该可以解决问题:

      const timestamp = firebase.firestore.Timestamp.fromDate(
                new Date('2020-02-12 00:00:00')
              )
      
      const snaps = await db.collection('notifications').where("specificDate", "==", timestamp).get()
      

      【讨论】:

      • 谢谢雷诺塔内克!!
      猜你喜欢
      • 2021-06-19
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2020-10-22
      • 2018-10-15
      相关资源
      最近更新 更多