gpt4 book ai didi

javascript - Firebase .push() 尝试添加到数据库,但失败了?

转载 作者:行者123 更新时间:2023-12-02 15:04:05 25 4
gpt4 key购买 nike

我有一个组件可以检查用户之前是否对帖子进行过投票。如果他们这样做了,那么他们就不能再次对该帖子进行投票。如果他们还没有这样做,那么他们就被允许这样做。

该代码对于添加第一个用户非常有用。 Firebase 创建一个唯一 key ,然后添加 upVotedBy: userKey。但是,如果我尝试以另一个用户身份登录并执行相同的操作,则不会为新用户添加记录。它也没有记录任何类型的错误。

如果我在投票时查看 Firebase,它会尝试使用唯一键添加新记录,然后变成红色并收回它。有任何想法吗?

编辑:我已经缩小了范围,看来如果已经有一条记录,任何记录,它都不会添加它。它将添加第一个记录,但不会添加任何后续记录。

我的数据结构如下:

Data Structure

这是组件:

handleUpVote: function(item){
var ref = new Firebase(rootUrl);
var authData = ref.getAuth();
if(authData){
var userKey = authData.uid;
console.log('this is userKey ' + userKey)
var stateCopy = Object.assign({}, item);
ref.child('items').child(this.props.keyNum).child('upVotedBy').once('value', function(snapshot){
snapshot.forEach(function(childSnapshot){
console.log('this is snapshot.key ' + childSnapshot.val().upVotedBy);
if(childSnapshot.val().upVotedBy === userKey){
this.setState({userUpvoted: true})
console.log('u already liked this')
}
}.bind(this))
}.bind(this)).then(function(){
if(this.state.userUpvoted === false){
console.log('okay u can like this')
stateCopy.upVotes += 1;
ref.child('items').child(this.props.keyNum).child('upVotedBy').push({
upVotedBy: userKey
}, function(error){
if(error){
console.log('push error: ' + error)
}
})
console.log(stateCopy.upVotedBy)
this.fb.update(stateCopy);
}
}.bind(this))

} else {
console.log('must be logged in to upvote')
}


},

最佳答案

喝点咖啡和答案:)如需更多解释或问题,请发表评论。

问题在于您保存赞成票的方式。我的建议是这样做:

-Items
-itemid1
-upvotedBy
-userA: true
-userB: true
-itemid2
-upvotedBy
-userA: false
-userB: true

在你检查时你必须做这样的事情:

ref.child('items').child(this.props.keyNum).child('upVotedBy').once('value', function(snapshot){
snapshot.forEach(function(childSnapshot){
if(childSnapshot.key() === userKey){
//see if it is upvoted using childSnapshot.val()
}
}.bind(this))
}

为了保存赞成票,你必须使用 set() 而不是 Push()

ref.child('items').child(this.props.keyNum).child('upVotedBy').child(userKey).set(true);

关于javascript - Firebase .push() 尝试添加到数据库,但失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35224313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com