我的数据库结构如下所示。我要做的是编写一个Firebase触发器,当'/ SCORES'节点的任何部分更新时,它将获得PlayerID的RoundScore并更新现有记录。
"SCORES" : {
"2017" : {
"Round_1" : {
"3" : {
"Emoji" : "",
"PlayerName" : "Person A",
"RoundScore" : 100
},
},
},
},
"SELECTIONS" : {
"2015" : {
"Round_1" : {
"TEAM A" : {
"18" : {
"emoji" : " ",
"playerName" : "Person A",
"position" : "POS"
},
"19" : {
"emoji" : " ",
"playerName" : "Person B",
"position" : "POS"
}
},
"TEAM B" : {
"54" : {
"emoji" : " ",
"playerName" : "Person C",
"position" : "POS"
},
"89" : {
"emoji" : " ",
"playerName" : "Person D",
"position" : "POS"
}
},
"TEAM C" : {
"227" : {
"emoji" : " ",
"playerName" : "Person E",
"position" : "POS"
},
"234" : {
"emoji" : " ",
"playerName" : "Person F",
"position" : "POS"
}
},
"TEAM D" : {
"239" : {
"emoji" : " ",
"playerName" : "Person G",
"position" : "POS"
},
"280" : {
"emoji" : " ",
"playerName" : "Person H",
"position" : "POS"
}
}
}
}
}
}
所以我希望数据库在触发后看起来像。
"SCORES" : {
"2017" : {
"Round_1" : {
"3" : {
"Emoji" : "", <------------ DUPLICATE FROM HERE
"PlayerName" : "Person A",
"RoundScore" : 100 <------------ AND HERE
},
},
},
},
"SELECTIONS" : {
"2015" : {
"Round_1" : {
"TEAM A" : {
"3" : {
"emoji" : "", <------------ INSERT HERE
"playerName" : "Person A",
"position" : "POS"
"RoundScore" : 100 <------------ AND HERE
},
},
},
}
到目前为止,我所写的内容仅适用于硬编码的teamID(上例中的TEAM A)。
exports.whenScoresUpdate = functions.database
.ref('/SCORES/{yearId}/{roundId}/{playerId}')
.onCreate((snap, context) => {
const newScoreData = snap.val();
const yearId = context.params.yearId;
const roundId = context.params.roundId;
const playerId = context.params.playerId;
const scoreObj = {
"RoundScore" : newScoreData.RoundScore,
"Emoji" : newScoreData.Emoji,
};
return admin.database().ref('/SELECTIONS/' + yearId + '/' + roundId + '/{teamId}/' + playerId).update(scoreObj);
答案 0 :(得分:0)
你真的离它不远!以下代码应该有效。以下是几点评论:
onCreate()
的其他触发器,例如onUpdate()
。请注意,您必须使用change.after.val();
代替snap.val()
;。teamId
的值。这不起作用:...roundId + '/{teamId}/' + playerId....
Promise.reject
update()
exports.whenScoresUpdate = functions.database
.ref('/SCORES/{yearId}/{roundId}/{playerId}')
.onUpdate((change, context) => {
const newScoreData = change.after.val();
const yearId = context.params.yearId;
const roundId = context.params.roundId;
const playerId = context.params.playerId;
const teamID = "A"; //<- adapt according to your needs
const scoreObj = {
"RoundScore": newScoreData.RoundScore,
"Emoji": newScoreData.Emoji,
};
return admin.database().ref('/SELECTIONS/' + yearId + '/' + roundId + '/' + teamId + '/' + playerId).update(scoreObj)
.catch(error => {
console.log(error);
//...
});
});