原生JS更新Firebase多个键时如何在路径中使用变量?
问题根源
你当前的写法会直接把变量名update_referral_path、new_referral_path作为对象的字符串键名,JavaScript默认不会读取变量的实际值作为对象键,所以才会把字面量字符串作为路径写入Firebase。
可行解决方法
方法1:使用ES6计算属性名(最简洁,推荐)
直接把变量用方括号[]包裹作为对象键,JS会自动读取变量的实际值作为键名,修改后的代码如下:
admin.database().ref().update({ [update_referral_path]: current_time, [new_referral_path]: generated_referral_code }, error => { if (error) { console.log("updateReferral failed") return false } else { console.log("updateReferral succeeded") return true } })
Firebase Admin运行的Node.js环境完全支持该语法,无需额外配置。
方法2:先构建更新对象再赋值(兼容旧JS环境)
如果需要兼容不支持ES6的旧环境,可以先初始化空对象,再通过方括号语法动态添加属性:
// 先构造更新对象 const updates = {} updates[update_referral_path] = current_time updates[new_referral_path] = generated_referral_code // 执行更新操作 admin.database().ref().update(updates, error => { if (error) { console.log("updateReferral failed") return false } else { console.log("updateReferral succeeded") return true } })
可选优化:路径定义用模板字符串简化
你原本的路径拼接代码可以用ES6模板字符串(反引号包裹)简化,避免多段字符串拼接出错:
const update_referral_path = `referrals/${referral_code.trim()}/${current_user_id}` const new_referral_path = `profile/${current_user_id}/user_dict/profile/referral_code`
内容的提问来源于stack exchange,提问作者TheNomadicAspie
相关产品推荐
相关产品推荐

