Transactions 如何在保持优先级的同时使用.transaction更新数据?
我没有找到任何关于如何使用“.transaction”更新Firebase中的值,同时也像“.setWithPriority”一样维护优先级的文档。我有这方面的工作,但只是寻找一些关于Firebase API最佳实践的反馈。以下是我正在使用的代码片段:Transactions 如何在保持优先级的同时使用.transaction更新数据?,transactions,firebase,Transactions,Firebase,我没有找到任何关于如何使用“.transaction”更新Firebase中的值,同时也像“.setWithPriority”一样维护优先级的文档。我有这方面的工作,但只是寻找一些关于Firebase API最佳实践的反馈。以下是我正在使用的代码片段: userScoreRef.once('value', function(snapshot) { if(snapshot.val() === null) { // Create a new participant.
userScoreRef.once('value', function(snapshot)
{
if(snapshot.val() === null) {
// Create a new participant.
userScoreRef.setWithPriority({ Participant: participant, CurrentScore: 0 }, 0);
}
else {
// Update participant score.
userScoreRef.child("CurrentScore").transaction(function(_currentScore) {
_currentScore++;
userScoreRef.setWithPriority({ Participant: participant, CurrentScore: _currentScore }, _currentScore);
return;})// DO NOT UPDATE WITH TRANSACTION! Let setWithPriority perform the data update.
}
})
如你所见,我是:
1) 从Firebase w/.transaction中提取当前值,2)使用.setWithPriority设置数据,最后3)只需返回事务调用即可取消它 这目前有点尴尬,但以下类似的方法应该可以奏效:
userScoreRef.transaction(function(user) {
if (user == null) {
return {
Participant: participant,
CurrentScore: 0,
'.priority': 0
}
} else {
user.CurrentScore++;
user['.priority'] = user.CurrentScore;
return user;
}
});
基本上,您可以向从事务返回的对象添加.priority来设置优先级。但不幸的是,无法在事务更新函数中获取当前优先级。幸运的是,在您的情况下,您不需要它,因为它只是CurrentScore