Angular Fire中如何将输入日期与Firestore的Timestamp字段对比查询
解决Firestore中Date对象与Timestamp字段的匹配问题
我来帮你搞定这个Firestore日期查询的坑!你遇到的问题核心在于类型不匹配:Firestore里的timeKey是Timestamp类型,而你传入的date是普通的JavaScript Date对象,哪怕两者代表的时间完全一致,直接用==比较也不会匹配成功。
下面给你两种可行的解决方案:
方案1:将Date对象转换为Firestore Timestamp
直接把你的date转换成Firestore的Timestamp实例,再用于查询,这样类型一致就能精准匹配了。
假设你用的是AngularFire(从代码里的this.firestore来看应该是),代码调整如下:
import { Timestamp } from '@angular/fire/firestore'; // 把JS Date转换成Firestore Timestamp const firestoreTimestamp = Timestamp.fromDate(date); // 用转换后的Timestamp进行查询 this.firestore.collection(DELIVERIES, ref => ref.where('timeKey', '==', firestoreTimestamp) );
如果是普通的Firebase JS SDK,转换方式类似:
import { Timestamp } from "firebase/firestore"; const firestoreTimestamp = Timestamp.fromDate(date);
方案2:查询某一天的所有记录(如果你的需求是匹配当天)
如果你的date是当天0点,而timeKey包含具体的时分秒,那直接用==可能找不到任何记录——因为几乎没有记录的时间刚好是0点整。这时候应该用范围查询,匹配当天的所有时间:
import { Timestamp } from '@angular/fire/firestore'; // 构造当天的起始和结束时间 const startOfDay = new Date(date); startOfDay.setHours(0, 0, 0, 0); // 当天0点0分0秒0毫秒 const endOfDay = new Date(date); endOfDay.setHours(23, 59, 59, 999); // 当天23点59分59秒999毫秒 // 转换成Timestamp const startTimestamp = Timestamp.fromDate(startOfDay); const endTimestamp = Timestamp.fromDate(endOfDay); // 查询当天的所有DELIVERIES记录 this.firestore.collection(DELIVERIES, ref => ref.where('timeKey', '>=', startTimestamp) .where('timeKey', '<=', endTimestamp) );
补充说明
Firestore的Timestamp支持毫秒和纳秒级精度,而JS Date只有毫秒级,不过Timestamp.fromDate()会自动处理精度转换,不用担心丢失信息。
试试上面的方法,应该就能顺利匹配到你要的记录了!
内容的提问来源于stack exchange,提问作者lyonTypescript
相关产品推荐
相关产品推荐

