Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  127] [ 7]  / answers: 1 / hits: 5354  / 4 Years ago, mon, october 19, 2020, 12:00:00

I'm having a difficult time deleting a node in a firebase realtime database.


This is what my firebase realtime database looks like:
enter


This is what I tried, following delete node in firebase and How to delete/remove nodes on Firebase:


1)


     let chatRef = db.ref("/chats");
var query = chatRef.orderByChild("uid").equalTo(chatId);
query.on("child_added", (snapshot) => {
snapshot.ref.remove();
});

With the above code, when I clicked to delete the entire data (all of the nodes, including chat) was deleted.


2)


      chatRef.limitToLast(1).once("value", (snapshot) => {
snapshot.forEach((deedSnapshot) => {
deedSnapshot.ref.remove();
});
});

I got this working as intended, but it only removes the last node in /chats, and I want to specify the chat/uid I want to remove.


3)


      let chatRef = db.ref("/chats");
chatRef.child("5ZuZvUyByDcbteclgpM0t08beVn1").remove();

This simply caused nothing to happen. I had this in a try/catch, and clicking on "delete" led to the try running, but no errors were caught. And nothing happened in the database.


4)


      let chatRef = db.ref("/chats/MJy8cxO85ldEnDScsWZ");
chatRef.remove();

Same outcome as number 3 above -- nothing happened, and no errors were caught in the try/catch.


UPDATE: I tried the following, but this removes the entire chats data instead of only the node I want deleted:


      let chatRef = db.ref("/chats");
chatRef
.orderByChild("uid")
.equalTo(chatId)
.once("value")
.then(function (snapshot) {
snapshot.forEach((childSnapshot) => {
//remove each child
chatRef.child(childSnapshot.key).remove();
});
});

More From » firebase

 Answers
5

Your fourth example should work, except you have a typo:


let chatRef = db.ref("/chats/MJy8cxO85ldEnDScsWZ");

It should instead be:


let chatRef = db.ref("/chats/-MJy8cxO85ldEnDScsWZ");

You're missing the "-" before "M".


[#2464] Wednesday, October 14, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
griffinr

Total Points: 242
Total Questions: 91
Total Answers: 105

Location: Indonesia
Member since Wed, Jul 7, 2021
3 Years ago
griffinr questions
Sat, Jul 18, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
Wed, Jun 5, 19, 00:00, 5 Years ago
;