node.jsfirebasegoogle-cloud-platformgoogle-cloud-firestoregoogle-cloud-functions

firebase firestore finding document by date timestamp fails


From my app, I create a document with a field of type Timestamp where it is initialized as below:

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

in the Firestore I see it stored as:

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

In the Firebase function, however, when I try to search this document I get nothing. The code looks like below:

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)
      });

This prints the server log like the below:

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 }

I am not sure what is the issue. If I use some other property like a number field then it works fine.

enter image description here


Solution

  • Firestore's timestamps use microsecond precision. So even if you call new Date() in code twice, one call after another, there will be a small difference between them, hence the behavior you see. Besides that, the == operator is commonly used to check the equality between numbers, not Date objects.

    According to your last comment:

    The time part does not matter just the date.

    As also @FrankvanPuffelen already mentioned in his comment, the best option that you have is to use the > or < operators. In such a case, the query will not return documents with a perfect match but documents where the field Date holds a timestamp value that is greater or less than a specific date.