简体   繁体   中英

firebase transaction dynamic key

I have the following JSON and I'm trying to add a transaction to "count" on the account of a logged in user, however firebase ads the dynamic key and I'm having trouble with the firebase reference in that regard.

{
  "accounts" : {
    "-KRPSyO4B48IpBnHBTYg" : {
      "count" : "100",
      "email" : "",
      "userId" : ""
    }
  },
  "products" : {
    "-KUKRafaNurpFhGF4jQa" : {
      "name" : ""
    }
  },
}

I was trying to make this work:

firebase.database().ref('accounts/' + accounts.id+'/count').transaction(function(value) {
  if (value) {
    value++;
  }
 return value;
});

which is all good aside from the fact that I do not know what the "accounts.id" is even when the user is logged in.

What is the correct way to update the count record of a logged in user?

You can get the logged in user details by:

var user = firebase.auth().currentUser;
if (user) {
    userId = user.uid
} else {
    // No user is signed in.
}

once you have the user ID your code should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM