我有一个小型应用程序,用户可以根据玩家最近在各种运动中的表现对他们进行投票赞成或反对。
当当前点击投票按钮时,投票者的 UID(通过 Google 登录)应该被推送到相应投票玩家的数据库中。像这样:
这是执行 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/