5

I am tring to query to a Firestore database to a collection and filter by date. I have a Timestamp field and i need to get the results when a field called "specificDate" is equal to 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});
});

No matter any combination ,i have no result.If i change "==" with "<" or ">" i have results. I am afraid the problem it s something related with the time,and i want to ignore that,i only care Year,Month and Day. The following images illustrates my firestore collection,with just one 1 item. enter image description here

I been researching and i am not lucky yet.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Al Xx
  • 89
  • 3
  • 10

2 Answers2

8

Give the query the range you want with an AND query. Since you don't care about matching the time precisely, give it the entire days range.

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()
Jan
  • 1,332
  • 9
  • 13
3

The following should do the trick, using the fromDate() method of the Firestore Timestamp to build the query:

const timestamp = firebase.firestore.Timestamp.fromDate(
          new Date('2020-02-12 00:00:00')
        )

const snaps = await db.collection('notifications').where("specificDate", "==", timestamp).get()
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121