37

I'm using Firestore and I would like to delete a field that is in a specific object. I can delete a field in a document thanks to :

fieldName: firebase.firestore.FieldValue.delete()

But if I have an object like :

songList {
songName1: "HelloWorld",
songName2: "AnotherSong",
songName3: "andTheLastOne"
}

In order to delete the field songName3, I won't be able to do something like :

songList.songName3: firebase.firestore.FieldValue.delete()

Is there a way to delete a field inside an object ? Or should I delete the whole object, rebuild it without the 3rd field and save it ?

Thanks in advance,

1

10 Answers 10

43

The "dot notation" with the special "FieldValue.delete()" should work.

Try this:

    Map<String, Object> deleteSong = new HashMap<>();
    deleteSong.put("songList.songName3", FieldValue.delete());

    FirebaseFirestore.getInstance()
        .collection("yourCollection")
        .document("yourDocument")
        .update(deleteSong);

It worked for me.

See: https://firebase.google.com/docs/firestore/manage-data/delete-data https://firebase.google.com/docs/firestore/manage-data/add-data

23

This work for me in general

firebase
  .firestore()
  .collection('collection-name')
  .doc('doc-id')
  .set({ songlist : {
    [songName]: firebase.firestore.FieldValue.delete()
  }
  }, { merge: true });
0
10

Found this topic today and want to add my solution. I am using the dot notation. The following will remove the specific song from the songlist by using firestore.FieldValue.delete();. I am using the Node.js firebase-admin package written in TypeScript:

import * as admin from 'firebase-admin';
export async function removeSong(trackId: string, song: string) {
    try {
        const updates = {};
        // Dot Notation - will delete the specific song from songList
        updates[`songList.${song}`] = admin.firestore.FieldValue.delete();
        // Not necessary, but it's always a good practice
        updates['updatedAt'] = admin.firestore.FieldValue.serverTimestamp();

        await firestore.collection('songs').doc(trackId).update(updates);
        return true
    } catch (error) {
        return null;
    }
}
1
  • Using your solution I was able to delete a nested field inside an object. However, I used firebase.firestore instead of admin.firestore. It seems to be working just as well.
    – Phrosen
    Feb 14, 2021 at 10:54
3

It did not allow me to comment above, but Manuel Borja's solution works and is pretty clean. Here is how I used it:

db.collection("coolcollection")
  .doc(id)
  .set(
    {
      users: {
        [firebase.auth().currentUser
          .email]: firebase.firestore.FieldValue.delete(),
      },
    },
    { merge: true }
  );

A few things to add: this works when the given field of the map exists and when it does not exist.

2

I had the same issue from Android using Kotlin, and I solved it with dot notation as well. For Android Kotlin users, that is:

 val songName: String = "songName3"
 val updatesMap = HashMap<String, Any>()
 updatesMap["songList.${songName}"] = FieldValue.delete()
 FirebaseFirestore.getInstance()
                  .collection("Your Collection")
                  .document("Your Document")
                  .update(updatesMap)

Hope this helps!

2

Simpler approach to handle maps/object

db.collection('Users').doc('key')
        .update({
            'products.keytext' : firebase.firestore.FieldValue.delete()
        })
        .then(() => {
            console.log('Success');
        })
        .catch((e) => {
            console.log('Error---->', e);
        });

This will remove object with a key keytext from products map.

2

The new recommended way is to use the exported method deleteField:

import { updateDoc, deleteField } from "firebase/firestore";

// Remove the 'songName3' field from the songList map in the document
await updateDoc(yourRef, {
    ['songList.songName3']: deleteField()
});
1
1

Caution: This does not work for Maps, only for Arrays!

You might be able to implement SongList as an array instead of a Map. Because for Arrays Firestore now has a dedicated function to remove an element from an array:

yourRef.update({
    songList: firebase.firestore.FieldValue.arrayRemove("SongName3")
});

Source: https://cloud.google.com/firestore/docs/manage-data/add-data#update_elements_in_an_array

1

Update the document with a Map which has a key you want to get deleted and value FieldValue.delete().

var collection = FirebaseFirestore.instance.collection('collection');
collection
  .doc('document_id')
  .update(
    {
      'songList.songName3': FieldValue.delete(),
    }
);
0
const deleteField = async () => {
    const FieldValue = firestore.FieldValue;
    const itemRef = firestore().collection('COLLECTION-NAME').doc('DOCUMENT-NAME');                                
    const res = await itemRef.update(
    'ELEMENT-NAME', FieldValue.delete() //'ELEMENT-NAME' OR Object.Field which equals to Parent Field Name.
)};
e.g.
{ 
    12345: { you: 'You', me: 'Me', we: '12345' },
    56789: { you: 'You', me: 'Me', we: '56789' },
}
const res = await itemRef.update(
    object.we, FieldValue.delete() //OR '12345', FieldValue.delete()
);
1
  • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
    – Ghost
    Jul 17, 2021 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.