Recursively Clean Firestore FieldValue.delete()

How to recursively remove delete methods from the document’s object you just updated and have in memory.

David Dal Busco
ITNEXT
Published in
4 min readOct 15, 2020

--

Photo by The Creative Exchange on Unsplash

This morning I had to improve a function we used in DeckDeckGo to recursively clean objects after persistence. Because I am currently quite busy but would not like to push my blogging habits too much on the side, I got the idea that this small “hack” would be a nice subject for a new blog post 🤗.

Introduction

When you use Cloud Firestore, in order to delete specific fields from a document, you have to use the FieldValue.delete() method when you update a document (as displayed in the documentation).

For example, your database contains a document such as the following:

{
description: 'Hello World'
}

You would have to use the above method to remove it, as setting it for example to null would not remove the attribute but “only” set its value to null .

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

const firestore = firebase.firestore();

const ref = firestore.collection('users').doc('david');
const user = {
description: firebase.firestore.FieldValue.delete()
};
await ref.update(user);

Thanks to this method, the above document’s example becomes {} in the database.

Issue

This method works like a charm but can lead to an issue. Indeed, if you are not refreshing your local object after its update, it will still contain the method FieldValue.delete() afterwards, which does not reflect its effective value in database.

Concretely, with our above example, if we would print out the user to the console, its output would be the following.

{
description: n {h_: n}
}

This can lead to some unexpected behavior in your application, if you are still using the object after its update, notably if it is a state.

To overcome this issue, one solution would be explicitly fetch the newly updated document from Firestore, what is also happening automatically if you have developed…

--

--