pks
pks

Reputation: 101

firebase.firestore.FieldValue.delete() not deleting field in document

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,

Upvotes: 3

Views: 2364

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

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.

Upvotes: 7

Related Questions