firebase - 在 Firebase 中将数据保存到子级

标签 firebase firebase-realtime-database

我有一个小型应用程序,用户可以根据玩家最近在各种运动中的表现对他们进行投票赞成或反对。

当当前点击投票按钮时,投票者的 UID(通过 Google 登录)应该被推送到相应投票玩家的数据库中。像这样:

enter image description here

然而,它目前正在这样做: enter image description here

这是执行 Firebase 工作的代码。我相信这是我错误的其中一行。

this.database.child(playerId).transaction

ref = firebase.database().ref('players/voters');

代码:

this.database = firebase.database().ref().child('players');

upvotePlayer(playerId) {
this.state.user ?
  this.database.child(playerId).transaction(function (player) {
    if (player) {
      console.log("UID: " + uid)
      var ref = firebase.database().ref('players/voters');
      ref.child(uid).set(1);
    }
    return player;
  })
  :
  console.log("Must be logged in to vote.")

  }

最佳答案

您将投票存储在此路径players/voters中,而它应该在此路径players/$playerId/voters

检查这个

this.database = firebase.database().ref().child('players');

upvotePlayer(playerId) {
    this.state.user ?
        this.database.child(playerId).transaction(function (player) {
            if (player) {
                console.log("UID: " + uid)
                var ref = firebase.database().ref('players/' + playerId + '/voters');
                ref.child(uid).set(1);
            }
            return player;
        })
        :
        console.log("Must be logged in to vote.")
}

transaction方法有 transactionUpdate 函数作为参数,它应该返回新值,而您没有返回任何值,而且我认为更好的解决方案是不使用事务

编辑:没有事务的解决方案

upvotePlayer(playerId) 
{
    if(this.state.user)
    {
        let ref = firebase.database().ref('players/' + playerId + '/voters');
        ref.child(uid).set(1);
    }
    else
    {
        console.log("Must be logged in to vote.")
    }
}

关于firebase - 在 Firebase 中将数据保存到子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48484397/

相关文章:

Firebase 云函数触发器

ios - 上传图片时 Firebase for iOS 错误 : object does not exist

javascript - 如何排除 Firebase 数据库树中的某些键

java - 与简单条件混淆

Firebase Cloud Functions 在实时数据库 onCreate 上获取数据

java - 如何使用 firebase 嵌套查询设置类的属性值?

ios - swift ,iOS : How do I extract data from my firebase database?

swift - 从 UIImagePicker 上传图片到 Firebase

android - 如何在 'debug' Firebase 数据库上运行调试应用程序版本

node.js - TypeError : rtdb. initStandalone 不是函数