0

I've read Firebase data consistency across multiple nodes, the multi update stuff works as expected, however I don't know how to do the following:

Let's say I have 2 collections: answers and posts. Now I want to write an answer to a post and increment the answers counter on the post object keeping the data consistent between collections. So the actual objects look similar to these:

post

{
   ...,
   answers: X
}

answer

{
   postID: <random string>,
   ...
}

As I said above, that link answers how to do a merged update, however, how can I be sure that the answers property will only be incremented/decremented (in case of deletion) by 1? What I have so far is this:

"answers": {
  ".validate": "newData.isNumber() && (newData.val() === data.val() + 1 || newData.val() === data.val() - 1)"
}

Obviously that would work (I assume, haven't tried), but that would still allow me to create a new answer and decrement the counter. How can I overcome that issue?

Community
  • 1
  • 1
Andrew
  • 2,063
  • 3
  • 24
  • 40
  • To keep a count in sync with the underlying collection, see http://stackoverflow.com/questions/37954217/is-the-way-the-firebase-database-quickstart-handles-counts-secure/37956590#37956590 – Frank van Puffelen Jul 01 '16 at 17:24
  • Thanks, will take a look! – Andrew Jul 01 '16 at 17:50
  • @FrankvanPuffelen One question though: your suggested method requires me to know the answer's key before the update, but I don't, since I want to push **and** update the counter the same time. Is this supported? I'm kinda getting confused. :/ – Andrew Jul 01 '16 at 18:47
  • Nvm, I can create a new key client side! I guess I just gotta read your answers on SO, lol. Thanks again! – Andrew Jul 01 '16 at 20:01
  • Not sure what you mean by "key". My code reads the voteCount before writing it. It essentially replaces Firebase's transaction mechanism with a custom one, so that it can use a multi-location update. – Frank van Puffelen Jul 01 '16 at 20:30
  • I meant that I can do something like `updates['answers/' + ref.push().key]` and then effectively push a new answer even if it's an "update". – Andrew Jul 01 '16 at 20:52

0 Answers0