Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific node from Firebase in JavaScript

how do I remove this specific node in my database as shown in this picture below? (the nickname will be different since I'm just testing it, if anyone confuses) enter image description here

I've tried

    const roomRef = firebase.database().ref(`allRooms/${rooms}`);

    roomRef.orderByChild('nickname').equalTo(`${username}`).once('value',(snapshot)=> {  
                   snapshot.ref.remove();  })

But it just delete all of my nodes in that room, thank you

like image 398
Codojojo Avatar asked May 15 '26 14:05

Codojojo


1 Answers

You're almost there.

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. And your code needs to handle the fact that `` is a list with something like:

roomRef.orderByChild('nickname').equalTo(username).once('value',(snapshot)=> {
  snapshot.forEach((userSnapshot) => {  
    userSnapshot.ref.remove();  
  })
})

The above runs a separate remove() call for each matching node. If you have only one (or a few) nodes with the same name, this is probably fine. But if you have more of them, consider using a single multi-path update to remove all nodes like this:

roomRef.orderByChild('nickname').equalTo(username).once('value',(snapshot)=> {
  let updates = {};
  snapshot.forEach((userSnapshot) => {  
    updates[userSnapshot.key] = null; // 👈 setting to null will remove the node
  })
  roomRef.update(updates); // 👈 send all updates in one call
})
like image 168
Frank van Puffelen Avatar answered May 18 '26 05:05

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!