1
votes

I want to delete a specific Field for all documents in Firestore, how can I do this? Since there is no document of this question on Firebase, Stackoverflow, etc. I know it is possible to delete a Field for a single Documents using the SDK, so I have no choice to fetch all the Documents from Firestore and delete the Field for each Collections by SDK's delete()?

For example, if remove 'first_name' from 'users'

Before

Collection : users

Document: A
{
  "id": "A",
  "first_name": "Sid",
  "last_name": "Wilson"
}

Document: B
{
  "id": "B",
  "first_name": "Joey",
  "last_name": "Jordison"
}

Document: C
{
  "id": "C",
  "first_name": "Chris",
  "last_name": "Fehn"
}

After

Collection : users

Document: A
{
  "id": "A",
  "last_name": "Wilson"
}

Document: B
{
  "id": "B",
  "last_name": "Jordison"
}

Document: C
{
  "id": "C",
  "last_name": "Fehn"
}
1
Is "users" and array in each document or each object in the array is a document of "users" collection?Dharmaraj
@Dharmaraj Sorry, i wrote it in a very confusing way, so i've corrected the example. I was describing it based on the json output from Firestore. My question is to delete a specific Field from all Documents in the collection(in this example, "users").Masayuki Nagashio
Unfortunately, there's no other way. You can try running the code I've posted in my answer.Dharmaraj
If my answer was helpful you can accept (✔) and upvote (🔼). Feel free to ask further queries.Dharmaraj

1 Answers

1
votes

Bulks writes are not possible in Firestore at the moment and to update any document you need a reference to it i.e. the document ID. That means you would have to read all the documents, get a reference to them and update them.

// Reading all documents
const colRef = firebase.firestore().collection("users")
const colSnapshot = await colRef.get()

const delField = {first_name: firebase.firestore.FieldValue.delete()}

// Array of update promises
const updates = colSnapshot.docs.map((doc) => colRef.doc(doc.id).update(delField))
// Run the promises simulatneously
await Promise.all(updates)

It'll cost N reads and write where N is number of documents but this seems to be the only way. Unless you have array of document IDs somewhere else (it'll prevent reads as you already know the doc IDs).