0

I want to use a variable as a key in dictionary using Firestore.

var uid = "123456";

await admin
          .firestore()
          .collection("shop")
          .doc(shopId)
          .update({
            "role.${uid}": "reader",
          });

But this above code doesn't work.

The result is here. enter image description here

How do I set the uid to role's key?

  • 1
    https://stackoverflow.com/questions/2462800/how-do-i-create-a-dynamic-key-to-be-added-to-a-javascript-object-variable – epascarello Mar 10 '23 at 18:56
  • I already tried `role[uid]`. But in this context the role dictionary doesn't be identified. Because only inside Firesotre data it is identified. So complier issued a error. `No value exists in scope for the shorthand property 'role'. Either declare one or provide an initializer` – taro Tanaka Mar 10 '23 at 19:06
  • If you want it to be `{ "role.123456" : "reader"}` it is `const uid = 123; var y = { [\`role.${uid}\`]: "reader" }; console.log(y);` – epascarello Mar 10 '23 at 19:21
  • It did work. Thank you. First I thought I should do `role[uid]`. But to create dynamic a dictionary should I use `[]` for overall, right? Is this the same way you showed me as the link? – taro Tanaka Mar 10 '23 at 19:33

1 Answers1

1

If I understand what you are trying to do correctly, you should be using a template literal (backticks) instead of a regular string (double-quotes).

eg:

await admin
          .firestore()
          .collection("shop")
          .doc(shopId)
          .update({
            [`role.${uid}`]: "reader",
          });
djm181
  • 106
  • 8
  • 1
    that is not going to work. You are going to get an error like `Uncaught SyntaxError: Unexpected template string` – epascarello Mar 10 '23 at 19:22
  • You are absolutely right - fixed it now – djm181 Mar 10 '23 at 19:31
  • It did success. Why is it a right way? I have not seen using both `[]` and `$()` simultaneously. If you know about the tips, please teach me. – taro Tanaka Mar 10 '23 at 19:37
  • The square brackets allow you to specify the key to set in the object you are passing to `update` using an expression rather than a symbol. The `${}` is performing the substitution in the string that is actually specifying the key. The `update` method sees none of this, and only receives the final result: an object that looks like `{ "role.123456" : "reader" }` – djm181 Mar 10 '23 at 19:56