Firebase - How to delete many entries at once?

前端 未结 1 456
萌比男神i
萌比男神i 2020-12-10 14:04

How do I delete all entries for the given push ID?

For example, let\'s say KoxoxwTqfb50E1Gvi9F push ID is in many locations of my datab

相关标签:
1条回答
  • 2020-12-10 14:16

    In order to delete multiple entries from your database, you need to know all those locations (refernces). So with other words, in the way you add data, you should also delete it.

    Assuming your database looks like this:

    Firebase-root
       |
       --- Users
       |     |
       |     --- userUid1
       |     |      |
       |     |      --- //user1 data
       |     |
       |     --- userUid2
       |            |
       |            --- //user2 data
       |
       --- Groups
             |
             --- groupId1
             |      |
             |      --- //group1 data
             |      |
             |      --- Users
             |            |
             |            --- userUid1: true
             |            |
             |            --- userUid3: true
             |
             --- groupId2
                    |
                    --- //group2 data
    

    I suggest you using the method below:

    private static void deleteUser(String userId, String groupId) {
        Map<String, Object> map = new HashMap<>();
        map.put("/Users/" + userId + "/", null);
        map.put("/Groups/" + groupId + "/Users/" + userId + "/", new HashMap<>().put(userId, null));
        //other locations
        databaseReference.updateChildren(map);
    }
    

    This method atomically deletes all those entries. Using these paths, you can perform simultaneous updates to multiple locations in the JSON tree with a single call to deleteUser() method. Simultaneous deletes made this way are atomic: either all updates succeed or all updates fail.

    Hope it helps.

    0 讨论(0)
提交回复
热议问题