Animesh Kumar
Animesh Kumar

Reputation: 237

Firebase "child_added" event

Firebase DB

I want a function to be called whenever a new child is added to "chat". I know this can be done using "child_added" event. However, from that function, I want to modify the newly created child.

So suppose a new child "123456" is added to chat and I want to update the "123456" object in the DB. I think I could solve the problem if I somehow manage to get the key (in this case it's 123456) of the newly added object. Is there a way to achieve this?

Upvotes: 0

Views: 874

Answers (2)

Sharat K S
Sharat K S

Reputation: 17

u can also use firebase cloud functions as well by putting a trigger, so that this can be handled by server.

export const onNewChatTrigger = functions.database.ref('chat/{chatId}').onCreate(event => {
    let key = event.params.chatId;
    let data = event.data.val();
    ...
});

Upvotes: 1

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

That should do the trick:

ref.on('child_added', function(childSnapshot, prevChildKey) {
  var key = childSnapshot.key;
  ...
});

You will find more info at:

https://firebase.google.com/docs/reference/js/firebase.database.Query#on

Upvotes: 1

Related Questions