如何更新 Firebase Firestore 中的动态字段名称?

Har*_*rma 2 javascript firebase reactjs react-native

我想在 React Native 中执行类似以下代码的操作:

await firestore()
      .collection('Users')
      .doc('ABC')
      .update({
        this.state.documentName: url,
      });
Run Code Online (Sandbox Code Playgroud)

但我需要this.state.documentName动态,但 VSCode 报告错误说':' expected.. 我缺少什么?

TypeScript 注释的图像

sam*_*man 6

你非常接近,为了计算字段名称,将其括在方括号中:

await firestore()
      .collection('Users')
      .doc('ABC')
      .update({
        [this.state.documentName]: url,
      });
Run Code Online (Sandbox Code Playgroud)

update()方法还接受键值对中的参数:

await firestore()
      .collection('Users')
      .doc('ABC')
      .update(this.state.documentName, url);
Run Code Online (Sandbox Code Playgroud)

注意:您应该确保采用适当的安全规则,以防止用户将自己提升为管理员(如果该信息也包含在用户文档中)。