Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a field from Firestore, with a dynamic key

Tags:

I am trying to delete a single field from a Document in Firestore The Key of the field is held in a variable e.g.

var userId = "random-id-1"

In the document I have a field of members structured like this:

{
  members:{
    random-id-1:true,
    random-id-2:true
  }
}

I would like to delete random-id-1:true, but keep random-id-2:true

How is this possible without getting the entire members object and writing an updated object?

I have tried this, however I get the error: Document references must have an even number of segments

and I also tried this:

db.collection('groups').doc(this.props.groupId).set({
  members: {
    [userId]: firebase.firestore.FieldValue.delete()
  }
},{merge: true})

However I get the error: Function DocumentReference.update() called with invalid data. FieldValue.delete() can only appear at the top level of your update data

Thanks for any help

like image 481
Finlay Percy Avatar asked Nov 23 '17 10:11

Finlay Percy


People also ask

How do I remove a field from firestore?

Deleting Fields For deleting a specific field from a document, use the FieldValue. delete() method when we update a document.

How do I remove a field from a document in firebase?

document("BJ"); // Remove the 'capital' field from the document Map<String,Object> updates = new HashMap<>(); updates. put("capital", FieldValue. delete()); docRef. update(updates).

How do I remove a map key from firestore?

The "dot notation" with the special "FieldValue. delete()" should work. Map<String, Object> deleteSong = new HashMap<>(); deleteSong.


2 Answers

I have managed to delete a field like this:

let userId = "this-is-my-user-id"
let groupId = "this-is-my-group-id"

db.collection('groups').doc(groupId).update({
  ['members.' + userId]: firebase.firestore.FieldValue.delete()
})

This is using the dot operator method described here

Please let me know if there are any alternative methods to this

Thanks

like image 121
Finlay Percy Avatar answered Oct 26 '22 21:10

Finlay Percy


I had to import FieldValue

https://firebase.google.com/docs/firestore/manage-data/delete-data#fields

        // Get the `FieldValue` object
        var FieldValue = require('firebase-admin').firestore.FieldValue;
        
        // Create a document reference
        var cityRef = db.collection('cities').doc('BJ');
        
        // Remove the 'capital' field from the document
        var removeCapital = cityRef.update({
          capital: FieldValue.delete()
        });
like image 38
Marcel Powolny Avatar answered Oct 26 '22 22:10

Marcel Powolny