How Can I Pass a Field Name Dynamically to Firestore's Update Method?

This topic was automatically generated from Slack. You can find the original thread here.

I am trying to use firestore sdk to delete a field in document . For that I need to pass the field name for update method dynamically which is throwing me an error . It says fieldname is undefined. How do I pass that dynamically in the update method??

you can add field as a prop in your Node code step. For example as the image below:

I have added that :import admin from ‘firebase-admin’;
import firestore from ‘firebase-admin’;
export default {
name: “DeleteField”,
description: "Delete a field of Firestore document ",
key: “del_field”,
version: “0.0.2”,
type: “action”,
props: {
path: {
type: “string”,
label: “Path”,
description: “A relative Path to the location of document”
},
field:{
type: “string”,
label: “Field”,
description: “Name of the field to delete”
},
firebase_admin_sdk: {
type: “app”,
app: “firebase_admin_sdk”,
}
},
async run() {
const { projectId, clientEmail, privateKey } = this.firebase_admin_sdk.$auth
const formattedPrivateKey = privateKey.replace(/\n/g, ‘\n’)
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert({
projectId,
clientEmail,
privateKey: formattedPrivateKey,
})
})
}
const db = admin.firestore();
const record = db.doc(this.path);

    **var** fieldname=**this**.field;
    record.update(
      {
        fieldname : firestore.DELETE_FIELD,
      }
    )
},

}

But fieldname I am unable to pass that in record.update method , it says fieldname is declared but not used

Ah I see, the fieldname on your code is not the dynamic value. You can try to change the last part your code to

       var fieldname=this.field;
        record.update(
          {
            [fieldname] : firestore.DELETE_FIELD,
          }
        )

Now I am able to pass fieldname dynamically , but the error still exists

could you console log all the values that sent to firestore (.i.e firestore.DELETE_FIELD) to debug which value is undefined?

Working . Using this code const res = await record.update({
[fieldname]: admin.firestore.FieldValue.delete()
});