Is it possible to somehow do it with startAt()
and endAt()
?
db.ref('/items')
.orderByChild('createdAt')
.endAt(new Date().getTime() 180 * 60 * 1000) // Updated
.on('value', () => {/* ... */})
Edit:
What I'm trying to achieve is getting all the items
that are currently in the database and listening for the newly added items
from the last n hours
.
Using a static number like endAt(1669743560642)
, lets say user is there for a few minutes, the number 1669743560642
will not be updated to the new time that has gone by, it's important to somehow that value gets somehow updated in real time.
So from (user's/server time) up to n hours
.
Exports from Realtime Database:
{
"items": {
"-NI3TAUjGNRlAUQ3Yc8K": {
"createdBy": "5gQ5cfGN15WCSa9RZVvAYXhKTyc2",
"createdAt": 1669743560642
},
"-NI3i-jMEyx_inQCaALr": {
"createdBy": "lc4BcHOls7cBuTVmbNo9LmtDdlf2",
"createdAt": 1669747710748
},
"-NI8-Jb_Qvd8gA3nG9cv": {
"createdBy": "5gQ5cfGN15WCSa9RZVvAYXhKTyc2",
"createdAt": 1669819620439
}
}
}
CodePudding user response:
It sounds like you want to get nodes with a createdAt
value of N hours ago or newer. For that I see two problems in your code:
- Since Firebase Realtime Database always orders the value in ascending order, that's a
startAt
operation, not anendAt
operation. - Since you want N hours in the past, you need to subtract from the current timestamp, not add to it.
So something like this:
db.ref('/items')
.orderByChild('createdAt')
.startAt(Date.now() - 8 * 60 * 60 * 1000) // 8 hours ago
.on('value', () => {/* ... */})
There is no way to make that startAt
value dynamic though. Once you create a query, it is immutable. So if you want the window of data to move, you'll have create another query for that.
In most cases where I need this, I actually end up post-filtering the nodes in my application code. So I create the query with the startAt
value as above, and then add additional logic to expire items locally too. When you have a limit
on the query too, that won't work or be harder, so I try to avoid needing that combination.