0

I have a little issue with correctly incrementing a value in a Realtime Database. Here is how it looks:

MyList
  + -M93jOoZSx443cxXXDKN
  - -M93jF4qK9MheZvAuX6k
      count: 0
      name: "GHD"
  + -M93jCPkGsW4swOZS0JL

Let us say I need to increment count, on the second item from 0 to 1.

This is very simple, nonetheless due to possible concurrent writings it has to be done right. And it is not easy to find out how to do it. I have read that we should use transaction, but haven't found the proper syntax for that. Beside many document do not state clearly if they apply to Realtime Database or not.

This document has an example that I tried to apply but was unsuccessfull.

I tried something like this (wrong):

var dbRef = firebase.database().ref('MyList/'+item.ref+'count');
dbRef.transaction(function(currentRank) {
  // If users/ada/rank has never been set, currentRank will be `null`.
  return count + 1;
});

To sum it up, my question is what is the correct way to increment my count?

Michel
  • 10,303
  • 17
  • 82
  • 179
  • What is currentRank's value inside the function? – Lajos Arpad May 24 '20 at 06:12
  • I do not even reach inside the function. The line "var dbRef = firebase.database().ref....." is already wrong. – Michel May 24 '20 at 06:42
  • What happens there? – Lajos Arpad May 24 '20 at 06:45
  • I get a message telling me the path is wrong. I should not be using item.ref. But the problem is I don't know what to use instead. How am I supposed to refer to the id? – Michel May 24 '20 at 06:50
  • What is the value of item.ref? Maybe 'MyList/count' would be more helpful. I'm not very knowledgable with Firebase, but I just try to help. – Lajos Arpad May 24 '20 at 06:59
  • OK. But there are many items in MyList, each having a count, as you can see looking at my post. How do I set the item? – Michel May 24 '20 at 07:02
  • In fact I have already caught the item in a snapshot using code like this: "dbRef.orderByChild('name').equalTo(param).once('value', function(snapshot) {". I just don't know the proper way to make use of this snapshot. – Michel May 24 '20 at 07:08
  • I would end the first line with an equalTo and hope that I can reuse it in the next line. – Lajos Arpad May 24 '20 at 07:15

0 Answers0