robinpdev
robinpdev

Reputation: 35

How to only read changes in firebase realtime database

I have a database collection with readings, each new reading needs to be checked if it's out of the ordinary, if it is, there needs to be an alert sent.

So i'm using db.ref('collection').on('child_added', (child => { check(child); }); The problem with the .on function is that when the listener is added, all previous data is also read.

So how do i read a collection that only reads the changes in the database, also when the listener is first added? Or if that doesn't work, how do I differentiate the already added data with the new data?

Upvotes: 2

Views: 880

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599541

The Firebase database synchronizes the state of whatever query or reference you attach your listener to. There is no option to only get new nodes built into the API.

If you want only new nodes, you will have to:

  1. Ensure each node has an associated timestamp or order. If you're using Firebase's built-in push() keys, those might already serve that function.
  2. Know what "new" means to the client, for example by either keeping the last timestamp or push key that it saw.
  3. And then use a query to only request nodes after the stores timestamp/key.

So for example, if you only want to read nodes that are created after the moment you attach the listener, you could do something like this:

let now = db.ref('collection').push().key; // determine current key
db.ref('collection').orderByKey().startAt(now).on('child_added', ...)

Upvotes: 2

Related Questions