TheNomadicAspie
TheNomadicAspie

Reputation: 275

Using variables in Firebase path with vanilla JS when updating multiple keys

I'm trying to update multiple paths at the same time with my Firebase database, but each path requires variables to define:

const update_referral_path = "referrals/" + referral_code.trim() + "/" + current_user_id
const new_referral_path = "profile/" + current_user_id + "/user_dict/profile/referral_code"

I'm using this code to update it, but Firebase as expected updates the database with the literal string "update_referral_path" and "new_referral_path."

    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
        }
    })

I've seen ways to use variables in Angular with backticks and double brackets, but I'm unsure how I can do this in vanilla JS and can't find any examples of people doing so? What are my options?

Upvotes: 0

Views: 135

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600131

To use the value of the variable in a key, use [] notation:

admin.database().ref().update({
    [update_referral_path]: current_time,
    [new_referral_path]: generated_referral_code
}, error => {
    ...

You can also build a literal JSON object outside of the update call:

let updates = {};
updates[update_referral_path] = current_time;
updates[new_referral_path = generated_referral_code;
admin.database().ref().update(updates);

Upvotes: 1

Related Questions