'How to delete a field in a Firestore Document?
How to delete a Document Field in Cloud Firestore? ... I'm using the code below but I can not.
this.db.doc(`ProfileUser/${userId}/followersCount/FollowersCount`).update({
[currentUserId]: firebase.firestore.FieldValue.delete()})
Is it possible, and if so, how?
Solution 1:[1]
This worked for me. (also worked to delete field with null value)
document.ref.update({
FieldToDelete: admin.firestore.FieldValue.delete()
})
Solution 2:[2]
With Firebase Version 9 (Feb, 2022 Update):
If there is the collection "users" having one document(dWE72sOcV1CRuA0ngRt5) with the fields "name", "age" and "sex" as shown below:
users > dWE72sOcV1CRuA0ngRt5 > name: "John",
age: 21,
sex: "Male"
You can delete the field "age" with this code below:
import { doc, updateDoc, deleteField } from "firebase/firestore";
const userRef = doc(db, "users/dWE72sOcV1CRuA0ngRt5");
// Remove "age" field from the document
await updateDoc(userRef, {
"age": deleteField()
});
users > dWE72sOcV1CRuA0ngRt5 > name: "John",
sex: "Male"
You can delete multiple fields "age" and "sex" with this code below:
import { doc, updateDoc, deleteField } from "firebase/firestore";
const userRef = doc(db, "users/dWE72sOcV1CRuA0ngRt5");
// Remove "age" and "sex" fields from the document
await updateDoc(userRef, {
"age": deleteField(),
"sex": deleteField()
});
users > dWE72sOcV1CRuA0ngRt5 > name: "John"
Solution 3:[3]
For some reason the selected answer (
firebase.firestore.FieldValue.delete()) did not work for me. but this did:
Simply set that field to null and it will be deleted!
// get the reference to the doc
let docRef=this.db.doc(`ProfileUser/${userId}/followersCount/FollowersCount`);
// remove the {currentUserId} field from the document
let removeCurrentUserId = docRef.update({
[currentUserId]: null
});
Solution 4:[4]
carefully using this admin.firestore.FieldValue.delete() Because query doesn't work if you try to delete not available field on the document.
So, I think it's better to set null
this.db.doc(`ProfileUser/${userId}/followersCount/FollowersCount`).update({
[currentUserId]: null})
OR
await db.doc(`ProfileUser/${userId}/followersCount/FollowersCount`)
.set({[currentUserId]: null}, { merge: true })
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dave |
| Solution 2 | |
| Solution 3 | mim |
| Solution 4 | BIS Tech |
