Reputation: 41
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"
}
Upvotes: 3
Views: 1618
Reputation: 50910
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).
Upvotes: 3