0

I need to delete the media object that has value "-LKJ60LdhSaJOzogSccL". In order to delete it, I have to retrieve its key which was previously generated with childByAutoId function.
How can I query media node by value? I need to query media node in order to get a single child which has a certain value.
This is what I tried and it returns null.

 let mediaUID = "-LKJ60LdhSaJOzogSccL"
 userUID = Q6Dm3IMLNLgBH3ny3rv2CMYf47p1

 let refUsers = Database.database().reference().child(users).child(userUID).child("media")
 refUsers.queryEqual(toValue: mediaUID).observeSingleEvent(of: .value, with: { (snapshot) in

        print("snapshot.value \(snapshot.value)")
 // prints null
        return
    })


users
   Q6Dm3IMLNLgBH3ny3rv2CMYf47p1
        email: "dondraper@gmail.com"
        fcmToken: "d1I..."

    media
     -LKJ61KoaUUrEt1JtfoS: "-LKJ60LdhSaJOzogSccL"
bibscy
  • 2,598
  • 4
  • 34
  • 82
  • The only thing I now spot is that you're missing `users` in your database reference: `Database.database().reference().child(userUID).child("media")`. – Frank van Puffelen Aug 20 '18 at 05:16
  • @FrankvanPuffelen, sorry, I only missed it in my question, but I had it in the original code – bibscy Aug 20 '18 at 06:10

1 Answers1

1

You're missing an instruction to order the child nodes, which means that Firebase (by default) orders and filters on the priority of the nodes. The solution is to order by value and then filter:

refUsers.queryOrderedByValue().queryEqual(toValue: mediaUID).observeSingleEvent(of: .value, with: { (snapshot) in

Since 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. You will need to handle that in your code by iterating over the results:

for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
   print(child.value)     
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • It works. I understand I need to iterate, though it is a unique object in the database since I get the data as a list. – bibscy Aug 20 '18 at 06:38
  • If the value is already unique, consider using it as the key. That way you won't need a query, but can just load it by its path: `/users/Q6Dm3IMLNLgBH3ny3rv2CMYf47p1/-LKJ60LdhSaJOzogSccL`. – Frank van Puffelen Aug 20 '18 at 23:12