简体   繁体   中英

How to update a dynamic field name in Firebase Firestore?

I want to do something like the below code in React Native:

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

But I need this.state.documentName to be dynamic but VSCode is reporting an error saying ':' expected. . What am I missing?

TypeScript 注释的图像

You were very close, in order to compute the field name, wrap it in square brackets:

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

The update() method also accepts arguments in key-value pairs:

await firestore()
      .collection('Users')
      .doc('ABC')
      .update(this.state.documentName, url);

Note : You should make sure to employ appropriate security rules to prevent a user from promoting themselves to an admin if that information is also contained in their user document.

Define the documentName from state outside of the async function in a variable then use it to update in the function

var db = firebase.firestore();
var documentName = this.state.documentName;
await db.collection("Users")
.doc('ABC')
.update({documentName: "bar"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM