我在每个客户端上使用查询“ OnUpdate”来从该节点获取数据并计算children-count,但这太昂贵了。
因此,我决定使用云功能,并基于所有用户都存在的节点创建另一个child-count节点,但是有一个问题,我无法找到任何类似“ OnChildAdded”的查询。
firebase文档上列出的可用查询是“ OnUpdate”,“ OnDelete”,“ OnWrite”和“ OnCreate”,在这种情况下是无用的,因为在子节点上使用“ OnCreate”无法返回父节点的子代或“ OnUpdate”。父节点将再次变得昂贵,因为所有用户都会频繁更新其状态。
那么“ OnOperation”呢?是否有使用它或有其他方法来降低查询成本并创建子计数节点?
这是我的数据库的结构
{
currentGame: {
players: {
playerId: {...playerGameData},
//,
},
noOfPlayer: // this is what i wanted to create based on above players node children_count.
}
}
如果有人需要解决类似的问题,这是上述问题的解决方案。
const PLAYER_REF = "currentGame/players/{playerId}";
const PLAYER_COUNT_NODE = "currentGame/noOfPlayers";
exports.incPlayersCount = functions.database.ref (PLAYER_REF).onCreate (async (snap) =>
{
const countRef = snap.ref.root.child (PLAYER_COUNT_NODE);
await countRef.transaction((current) => {
return (typeof current !== "number" || current < 0) ? 1 : current + 1;
});
return null;
});
exports.decPlayersCount = functions.database.ref (PLAYER_REF).onDelete (async (snap) =>
{
const countRef = snap.ref.root.child (PLAYER_COUNT_NODE);
await countRef.transaction((current) => {
return (typeof current !== "number" || current <= 0) ? 0 : current - 1;
});
return null;
});
顺便说一句-它与@FrankvanPuffelen在上述注释中共享的示例代码完全相似。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句