I’m trying out the node.js Admin SDK to push items and listen to updates on a Realtime Database:
ref.child('something').on('child_added', childAdded)
ref.child('something').on('child_changed', childChanged)
ref.child('something').on('child_removed', childRemoved)
...
ref.child('something').push({...})
If I push 3 items, I expect to get childAdded
to be called 3 times with each item. Sometimes this is what happens, other times this (after the 3rd add):
childRemoved
called twice for the 2 existing items
childAdded
called 3 times for the 2 existing items and the new item
Is this normal? How can I avoid child_removed
callbacks for existing items?
2
Answers
It turns out the strange was behavior was caused by a transaction on the parent object as part of adding/removing children.
The transaction was sometimes being called with no data, in which case I was returning an empty/placeholder object and that was apparently causing
child_removed
events to be fired. The transaction would run again with actual data and the children would seemingly added back.Solution: Set the
applyLocally
parameter of the transaction tofalse
.It sounds like you have a
limit
on your query, in which case this is the expected behavior.A Firebase Realtime Database query gives you a view on the subset of the data. Say that you have a node with chat messages, and you create a query to get the last 3 chat messages:
Initially this will give you the 3 most recent chat messages, say with timestamps:
Now let’s say somebody adds a new chat message with timestamp:
The database will now fire a
child_added
event for the new child node, and achild_removed
event for the oldest one of the snapshot it gave you before to ensure that your still have the latest 3 messages as you requested in the query.