使用Firebase dbRef.update()时能否生成Firebase自带随机键?
问题:Firebase Realtime Database多字段更新时能否获取自动生成的键?
在Firebase Realtime Database中,我需要同时更新多个字段,包括创建新节点,示例代码如下:
const updates = { [`players/${data.playerId}/budget`]: database.ServerValue.increment(-1 * actionS.val().cost), [`players/${data.playerId}/actions/${data.actionId}/position`]: "discard", // 不能用action id,因为它可能被多次使用,所以生成随机id [`solutions/${data.projectId}/investments/${uuid()}`]: actionS.val(), }; await gameRef.update(updates);
发现Firebase自带的键默认有序,但自行生成的uuid会打乱排序,请问使用dbRef.update()进行多字段更新时,能否获取Firebase生成的键?
可以实现,但不能直接通过update()方法获取Firebase自动生成的键。因为update()要求提前指定所有要更新的路径,而Firebase的有序推键是通过ref.push()生成的,这个方法会返回包含新键的引用。
解决思路是提前生成Firebase推键,再将其加入更新对象中,这样既保留update()原子更新的特性,又能拿到有序的系统生成键:
// 先为目标节点生成Firebase推键 const newInvestmentKey = gameRef.child(`solutions/${data.projectId}/investments`).push().key; // 构建更新对象,使用生成好的推键 const updates = { [`players/${data.playerId}/budget`]: database.ServerValue.increment(-1 * actionS.val().cost), [`players/${data.playerId}/actions/${data.actionId}/position`]: "discard", [`solutions/${data.projectId}/investments/${newInvestmentKey}`]: actionS.val(), }; await gameRef.update(updates); // 直接使用提前生成的newInvestmentKey即可 console.log("新生成的Firebase有序键:", newInvestmentKey);
这种方式既解决了uuid打乱排序的问题,又能保证所有更新操作的原子性。
内容的提问来源于stack exchange,提问作者Akasha
相关产品推荐
相关产品推荐

