how delete a specific node in firebase?
I hooked up firebase and made the save data in it. But I can't delete a specific entry in firebase.
I tried deleting through method that I wrote below. But it doesn't work.
final FirebaseDatabase _database = FirebaseDatabase.instance;
delData(String phoneNumber) {_database.reference()
.child('phoneNumber')
.remove()
.then((_) {
print("Delete $phoneNumber successful");
setState(() {
//
});
});
}
Update
the method that I was advised by Frank van Puffelen does not work correctly, it removes all entries with the phoneNumber field, and I need to delete the entry with the phone number under which the user is authorized. In addition, the method listens when new notes are added with the phoneNumber field and deletes them automatically
removeNode() {
FirebaseDatabase.instance.reference()
.child('customers')
.orderByChild('phoneNumber')
.equalTo(phoneNumber)
.onChildAdded.listen((Event event) {
FirebaseDatabase.instance.reference()
.child('customers')
.child(event.snapshot.key)
.remove();
}, onError: (Object o) {
final DatabaseError error = o;
print('Error: ${error.code} ${error.message}');
});
}````
// This is how is i add data to DB
````void handleSubmit() {
final FormState form = formKey.currentState;
print(userPhone);
if (form.validate()) {
form.save();
form.reset();
itemRef.push().set(item.toJson());}````
Maybe I should use firestore?
In order to delete a node, you need to know the complete path to that node. If you don't know that complete path, you can use a query to determine it.
So in your case, if you know the phone number of the node you want to delete, you can query for all nodes with that phone number (since there may be multiple) and then delete them.
The code for this would look something like:
FirebaseDatabase.instance.reference()
.child('customers')
.orderByChild('phoneNumber')
.equalTo('+79644054946')
.onChildAdded.listen((Event event) {
FirebaseDatabase.instance.reference()
.child('customers')
.child(event.snapshot.key)
.remove();
}, onError: (Object o) {
final DatabaseError error = o;
print('Error: ${error.code} ${error.message}');
});
Update (20200221): You can also use a once()
listener and loop over its child nodes with:
FirebaseDatabase.instance.reference()
.child('customers')
.orderByChild('phoneNumber')
.equalTo('+79644054946')
.once()
.then((DataSnapshot snapshot) {
Map<dynamic, dynamic> children = snapshot.value;
children.forEach((key, value) {
FirebaseDatabase.instance.reference()
.child('customers')
.child(key)
.remove();
})
});