skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 to false.


  2. 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:

    ref.child('messages').orderByChild('timestamp').limitToLast(3)
    

    Initially this will give you the 3 most recent chat messages, say with timestamps:

    • 1677076200112
    • 1677076200175
    • 1677076200196

    Now let’s say somebody adds a new chat message with timestamp:

    • 1677076222060

    The database will now fire a child_added event for the new child node, and a child_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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search