TDG
TDG

Reputation: 6151

Deleting a record from Firebase by ID

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.

Upvotes: 0

Views: 3835

Answers (1)

Mike
Mike

Reputation: 2559

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);
          })
        });

Upvotes: 1

Related Questions