1

With Firebase fan out data to different nodes and paths is recommended by Firebase like below example from Firebase sample:

{
  "post-comments" : {
    "PostId1" : {
      "CommentID1" : {
        "author" : "User1",
        "text" : "Comment1!",
        "uid" : "UserId1"
      }
    }
  },
  "posts" : {
    "PostId1" : {
      "author" : "user1",
      "body" : "Firebase Mobile platform",
      "starCount" : 1,
      "stars" : {
        "UserId1" : true
      },
      "title" : "About firebase",
      "uid" : "UserId1"
    }

  },
  "user-posts" : {
    "UserId1" : {
      "PostId1" : {
        "author" : "user1",
        "body" : "Firebase Mobile platform",
        "starCount" : 1,
        "stars" : {
          "UserId1" : true
        },
        "title" : "About firebase",
        "uid" : "UserId1"
      }

    }
  },
  "users" : {
    "UserId1" : {
      "email" : "user1@gmail.com",
      "username" : "user1"
    }
  }
}
  1. With multipath updates we can atomically update all the paths for a post, however if we want to delete a blog post in above kind of schema then how can we do it atomically? There is no multi path delete, I guess. If client losses network connection while deleting then only few paths would be deleted!

  2. Also in case there is a requirement like when a user is deleted for all the post he has starred, we should remove the stars and unstar the post for that user. This becomes difficult as there is no direct tracking of what posts user has starred. For this do we need to fan out the starring of posts as well like have a node user-stars. Then while deleting we know what all activity the user has done and act on it while deleting user. Is there a better way of handling this?

    "user-stars":{
        "UserId1":{
            "PostID1":true  
        }
    }
    

In both cases the question on atomically or consistently deleting the data from multipaths (either all or nothing) is seemingly not available.

In that case the only option available looks to be putting the delete command in Firebase queue which will resolve the task in queue only if everything is deleted. That will be eventually consistent option but should be fine. But that is expensive option requiring server. Is there a better way?

AL.
  • 36,815
  • 10
  • 142
  • 281
Abhijit-K
  • 3,569
  • 1
  • 23
  • 31

1 Answers1

9

You can implement a multi-path delete, by writing a value of null to the paths.

So:

var updates = {
  "user-posts/UserId1/PostId1": null,
  "post-comments/PostId1": null,
  "posts/PostId1": null
}
ref.update(updates);

I had already answered this before: Firebase -- Bulk delete child nodes

It's also quite explicitly mentioned in the documentation on deleting data:

You can also delete by specifying null as the value for another write operation such as set() or update(). You can use this technique with update() to delete multiple children in a single API call.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807