2

I'm trying to delete a field in a Firebase document from a React app using firebase.firestore.FieldValue.delete() but it isn't working. Reading and writing data to documents and collections is working fine but I am struggling to get FieldValue to work. I've set up the Firebase instance in src/firebase.js like this:

import app from 'firebase/app';
import 'firebase/firestore';

var config = {
  ******
};

class Firebase {
  constructor() {
    app.initializeApp(config);
    this.fv = app.firestore.FieldValue;
    this.db = app.firestore();
  };
};

export default Firebase;

And then in the module that I am trying to use FieldValue in I am doing:

import Firebase from "./firebase.js";

class App extends Component {
  constructor(props) {
    super(props);
    this.firebase = new Firebase();
    this.db = this.firebase.db;
    this.fv = this.firebase.fv;
  };

  deleteFunction(id) {
    this.db.collection("collection_id").doc("doc_id").update({
      field_id: this.fv.delete()
    });
  }
};

However no variation of imports or doc references as mentioned here have been successful for me. I don't receive any errors and I know that the firestore instance is working correctly because I am using it to set and read the same data. I have also verified that the field_id I am trying to delete is the correct id and that this.fv is FieldValue by console logging them both.

What am I missing? I feel like this should be super easy and straight forward and that I am overlooking something super obvious,

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
pks
  • 91
  • 1
  • 8
  • I just tried using `"test"` as a field id and did: `this.db.collection("collection_id").doc("doc_id").update({ "test": this.firebase.fv.delete() });` and it worked. Why won't it delete a dynamic field id? – pks Jan 06 '20 at 15:02
  • 1
    What is `field_id` in your code meant to be? – Frank van Puffelen Jan 06 '20 at 15:16
  • I'm generating some id's for fields on the front end and using them to reference values in a document. – pks Jan 07 '20 at 00:18

1 Answers1

6

My guess is that you're trying to delete the field that is identified by field_id, so say:

// THIS WON'T WORK
let field_id = "fieldToDelete";
this.db.collection("collection_id").doc("doc_id").update({
  field_id: this.fv.delete()
})

The above code is trying to delete the literal field_id field, which probably doesn't exist.

You'll need to use [] notation to build the object you pass to Firestore.

let field_id = "fieldToDelete";
let updates = {};
updates[field_id] = this.fv.delete()
this.db.collection("collection_id").doc("doc_id").update(updates)

Now you're using the value of field_id in the call to Firestore, and it will delete fieldToDelete.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807