1

I have this database structure:

enter image description here

I am trying to get the node value (for example: -KzjZJvEQRBlRG8m2RxO) if the objectId value is equal to a specific value.

Let me give you an example: if the object id is equal to "-Kzx6b-w3cbE_3e1MwWr" then i would like to get the node value (-Kzx6bVxJHq0HgDjkhH8) so i can delte the record.

I tried to do it like so:

let query =  Api.Notification.NOTIFICATION_REF.queryOrdered(byChild: "objectId").queryEqual(toValue: id)
query.observeSingleEvent(of: .value, with: { (snapshot) in
  for snap in snapshot.children {
   print (snap.key)
}

However i get no value in the print statement Actually is seem not to enter at all the for cycle.

Is there a way to achieve this?

Thank you!

-----UPDATE Would a solution like this affect the speed if i get many records?

Api.Notification.NOTIFICATION_REF.observeSingleEvent(of: .value, with: { (snapshot) in
                for child in snapshot.children {
                    let snap = child as! DataSnapshot
                    let key = snap.key

                    Api.Notification.NOTIFICATION_REF.child(key).observeSingleEvent(of: .value, with: { (userid) in
                        for subChild in userid.children {
                            let subSnap = subChild as! DataSnapshot
                            let subKey = subSnap.key
                            //get the value here
                        }

                    })
                }
            })
Marco
  • 1,051
  • 1
  • 17
  • 40
  • is there any reason why objectId value is different from the node name? – Oxthor Nov 27 '17 at 13:46
  • yes they are different because based on the type i need different node name... i need to have for example, a value equals to followeuserId-followinguserId if type is following... and so on... – Marco Nov 27 '17 at 13:51
  • What does `NOTIFICATION_REF` point to? – Frank van Puffelen Nov 27 '17 at 15:22
  • @FrankvanPuffelen to the main node: Database.database().reference().child("Notification") – Marco Nov 27 '17 at 15:23
  • That means that the path you're trying to query contains two dynamic keys. Firebase Database can only query properties at a fixed path under each child of the node where you run the query. Also see my answer here: https://stackoverflow.com/questions/27207059/firebase-query-double-nested – Frank van Puffelen Nov 27 '17 at 15:37
  • @FrankvanPuffelen by dynamic keys you mean a key created with childbyautoId? i've Updated my question... – Marco Nov 27 '17 at 15:40

1 Answers1

0

Use snap.ref.parent?.key

Example:

query.observe(.value, with: { snap in
   guard let text = snap.value as? String else { return }
   print("snap parent key: \(snap.ref.parent?.key)")
}
LucasKarlsson
  • 1,021
  • 1
  • 10
  • 16