Home > front end >  Firestore get last 24 hours documents from collection - Node
Firestore get last 24 hours documents from collection - Node

Time:06-22

I want to get the documents which comes under last 24 hours, for each document I have set a field timestamp as:

admin.firestore().collection('users').set({..., timestamp: new Date().toJSON() })

Now, in my cloud function, I want to get the docs which comes under last 24 hours only, so for that I came up with the logic:

const end = new Date();
const start = new Date(end.getTime() - (24 * 60 * 60 * 1000)); // 24 hours ago

const users = await admin
                .firestore()
                .collection('users')
                .where('timestamp', '>', start)
                .where('timestamp', '<', end)
                .get();

But this returns nothing.

I also tried this question which was asked earlier: enter image description here

CodePudding user response:

Since the timestamp field in your database is stored as a string value, you also have to pass string values for conditions on that field:

admin
.firestore()
.collection('users')
.where('timestamp', '>', start.toJSON())
.where('timestamp', '<', end.toJSON())

Without that you're comparing strings and dates, and no value will every meet the condition in that case.

  • Related