0
votes

I'm trying to delete records from my FireBase DB, based on the record's ID, but the records are not being deleted.
I've read SO posts like How to delete/remove nodes on Firebase, remove-item-from-firebase and few more, but I cannot solve my problem.

The database's structure is:

my_project  
|  
|-messages  
 |+Kg87....  
 |+Kg9a....  
 |+and so on...  

My code:

const firebaseConfig = {
    apiKey: "AIza....",
    authDomain: ".firebaseapp.com",
    databaseURL: "https://myProject.firebaseio.com",
    storageBucket: "myproject.appspot.com",
    messagingSenderId: ""
};

firebase.initializeApp(firebaseConfig);
exports.delete =
functions.database.ref('/messages/{pushId}/text')
    .onWrite(event => { 
        var db = firebase.database();
        var ref = db.ref("messages");
        //console.log(ref.child("-Kg9a...").toJSON()); //- OK prints https://myproject.firebaseio.com/messages/Kg9a...
        ref.child("-KgOASNRfF2PheKQ6Yfu").remove();  //Does nothing, returns promise - pending
    });

To my understanding ref is a reference to the messages node, so ref.child("Kg9a....") is a reference to the desired child.

  • I don't get any error, but nothing happens. The record remains in the DB.
  • If I change the last line to console.log(ref.child("Kg9a....").remove()); I see that the log says Promise { <pending> } but even after few hours nothing happens.

  • This is not a security rule issue - I've set my security rules to ".read": true, ".write": true and it still doesn't delete the record.

  • My firebase version is 3.5.0 - I've installed 3.7.1, but when I run firebase -V I get that the version is 3.5.0.
    Any advice?
1
Can you please add the actually code you are using? A jsFiddle example would be awesome. - adolfosrs
@adolfosrs - I've added the full code. I'm running it from the firebase's console. - TDG

1 Answers

1
votes

A few changes to get that working. I assume you really want to delete the record that triggered the event, not the literal string ID in your example. You needed to return the promise you were getting back from remove() though I have found even having a then() handler will work but since returning it is documented as necessary I usually do both. Promises are like result/return codes, usually not to be ignored.

var someId = '-KgOASNRfF2PheKQ6Yfu';
exports.delete =
    functions.database.ref('/messages/{pushId}/text')
        .onWrite(event => {
          if (!event.data.exists()) return;
          var ref = event.data.adminRef.root.child('/messages').child(someId);
          return ref.remove().then(function(){
            console.log('OK, gone');
          }).catch(function(e){
            console.log('OOPS, problem: ' + e.message);
          })
        });