firebase firestore 按日期时间戳查找文档失败

问题描述 投票:0回答:1

在我的应用程序中,我创建带有 Timestamp 类型字段的文档,其初始化如下

 Date:Timestamp 
...
constructor(){
     const now = new Date()
     this.Date = Timestamp.fromDate(new Date(now.getFullYear(), now.getMonth(), now.getDate()));
   }

在 firestore 中我看到它存储为:

Date: October 7, 2024 at 12:00:00AM UTC-5

然而,在 firebase 功能中,当我尝试搜索此文档时,我什么也没得到。代码如下所示:

const now = new Date()
const ts:Timestamp = Timestamp.fromDate(new Date(now.getFullYear(), now.getMonth(), now.getDate()))
 const finColRef = db.collection("users/" + mapKey + "/finance")
      const fQuerySnapshot = await finColRef.where("Date", "==", ts).get()//
      fQuerySnapshot.forEach((doc:any) => {
        let data:any 
        data = doc.data()
        logger.log("fin data is::", data)
      });

这将打印服务器日志,如下所示:

INFO 2024-10-08T05:06:06.189902Z Processing map user:HEkDmm3r3HggtDYIkzCOkLFjPpa2 uid:
INFO 2024-10-08T05:06:06.189877Z another timestamp to find data is: Timestamp { _seconds: 1728345600, _nanoseconds: 0 }

我不确定是什么问题。如果我使用其他一些属性(例如数字字段),那么它就可以正常工作。

enter image description here

node.js firebase google-cloud-firestore google-cloud-functions
1个回答
0
投票

Firestore 的时间戳使用微秒精度。因此,即使您在代码中一次又一次地调用

new Date()
两次,它们之间也会有微小的差异,因此您会看到这样的行为。除此之外,
==
运算符通常用于检查数字之间的相等性,而不是
Date
对象。

根据您最后的评论:

时间部分与日期无关。

因此,在这种情况下,正如 @FrankvanPuffelen 在他的评论中已经提到的那样,最好的选择是使用

>
<
运算符。在这种情况下,查询将不会返回完全匹配的文档,而是返回字段
Date
包含大于或小于特定日期的时间戳值的文档。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.