首页 > 解决方案 > 按 DATE 的 Firestore Cloud Function 查询

问题描述

我正在尝试向 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 件。 在此处输入图像描述

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

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


使用 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()

推荐阅读