如何在Firestore中正确基于timestamp字段进行数据筛选
问题原因
Firestore的范围查询要求比较的两侧数据类型完全一致,你当前用字符串格式的日期和createdTime字段的Timestamp原生类型做比较,类型不匹配导致范围筛选规则无法触发。你之前等于查询能返回结果,仅属于部分文档createdTime实际存了字符串格式日期的巧合,本身也不符合规范。
正确实现步骤
1. 日期转换为Firestore Timestamp对象
先把你要筛选的日期字符串转为Firestore认可的Timestamp类型:
// 处理DD/MM/YYYY格式的目标日期 const targetDateStr = "10/08/2012"; const [day, month, year] = targetDateStr.split("/"); // JS月份从0开始计数,所以月份要减1,这里默认取当天零点作为比较基准 const targetDate = new Date(year, Number(month) - 1, day, 0, 0, 0, 0); // 转为Firestore Timestamp对象 const targetTimestamp = firebase.firestore.Timestamp.fromDate(targetDate); // 若使用v9+模块化SDK,写法改为: // import { Timestamp } from "firebase/firestore"; // const targetTimestamp = Timestamp.fromDate(targetDate);
2. 执行范围查询
用转换后的Timestamp对象做比较即可正常生效:
const jobRef = firestore1.collection("jobs"); // 晚于指定日期 const laterRes = await jobRef.where("createdTime", ">", targetTimestamp).get(); // 早于指定日期 const earlierRes = await jobRef.where("createdTime", "<", targetTimestamp).get(); // 匹配指定日期全天的数据 const sameDayRes = await jobRef .where("createdTime", ">=", targetTimestamp) .where("createdTime", "<", Timestamp.fromDate(new Date(targetDate.getTime() + 86400000))) .get();
注意事项
- 首次对
createdTime做范围查询前需要在Firestore控制台建立对应索引,查询报错时会直接生成索引创建的快捷入口,点击等待索引创建完成即可。 - 不要混用字符串和Timestamp类型做日期比较,否则后续排序、聚合操作也会出现异常。
关联配置截图

内容的提问来源于stack exchange,提问作者Jeewantha
相关产品推荐
相关产品推荐

