londonfed
londonfed

Reputation: 1220

How to query child in Firebase database and then delete node

I have the following database setup in Firebase:

Firebase Screenshot

I am trying to write a script that searches within media (in all users) and returns a match if any particular media url matches the url argument I pass through. And if a match is returned I would like to remove this media key/node. However, my script is just returning null. Any ideas?

const ref = firebase.database().ref('/users/');
const url = 'https://XXXXXX.s3.amazonaws.com/profiles/william/1478471907-me.jpg';

return ref.child('media').orderByChild('url').equalTo(url).once("value").then(function(snapshot) {
   console.log(JSON.stringify(snapshot.val()));
});

Upvotes: 1

Views: 1348

Answers (1)

londonfed
londonfed

Reputation: 1220

Ok thanks to Imjared's feedback I've found a solution - including a way to remove the node:

// reference the media, B4K... could be an variable to target the correct key
const ref = firebase.database().ref('/users/B4KWeemv78R2GP7Jqul2f70kVM73/media');

return ref.orderByChild('url').equalTo(url).once("value").then(function(snapshot) {
  // get the key of the respective image
  const key = Object.keys(snapshot.val())[0];

  // delete image node from firebase
  ref.child(key).remove();

  return {
    success: 1,
    message: 'Image deleted.'
  };
}

Upvotes: 2

Related Questions