0

So I have this structure:

enter image description here

And my question is: How can I remove every field with the id of 3Q41X2tKUMUmiDjXL1BJon70l8n2 from every subject. I'm thinking about something like this:

admin.database().ref('UsersBySubjects')
    .child('subjects')
    .child(/variable/)
    .child(uid).remove().catch(e => console.log(e));
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Alex Ironside
  • 4,658
  • 11
  • 59
  • 119

1 Answers1

3

Hers the below code that should make it possible to do what you are trying. Basically just a query to get all the id's, the remove is a promise so you would probably want to add in async await to deal with promises to make sure its actually deleted before going to the next one

admin.database().ref('UsersBySubjects/subjects')
                .orderByChild('3Q41X2tKUMUmiDjXL1BJon70l8n2')
                .equalTo('3Q41X2tKUMUmiDjXL1BJon70l8n2')
                .on('value', (snapshot) => {
                    snapshot.forEach((result) => {
                       result.ref.remove()
                    })
                 })
Jack Woodward
  • 991
  • 5
  • 9
  • While this works, it requires that you define an index on each UID property. For a more scalable solution, see https://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value and https://stackoverflow.com/questions/41527058/many-to-many-relationship-in-firebase. – Frank van Puffelen Nov 15 '18 at 16:02
  • Very valid point. I tend to use Firestore exclusively now, much better query capabilities – Jack Woodward Nov 15 '18 at 16:04
  • 1
    There you'd use the new `array-contains` family of operators for this: https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html I really need to start using those myself, but... time :-/ – Frank van Puffelen Nov 15 '18 at 18:13