my firestore stores user data as below:
users (collection)
uid-123 (document one per user)
profile:
name: 'My Name'
options: {
x: 1,
y: 2,
z: 3
}
In a situation i want to remove y:2 from the profile.options. I am using like below:
async updateUserProfileMerged(uid: string, payload: any) {
try{
const userDocRef = doc(this.firestore, 'users/' + uid);
return setDoc(userDocRef, Object.assign({},{"profile": payload}), { merge: true });
}catch(err){
console.log("error in updateUserProfileMerged in data.service.ts:", err)
}
}
The passed payload in this case is:
options: {
x:1,
z: 3
}
This does not remove y as it is passing merge true. if i set merge to false then it will override the entire profile object. so how do i only override options?
If you want to delete a field in a document, you should use the documented deleteField function as the value for a field update. And, since you're using a nested field, you should use dot notation to specify the name of the field to delete. Given these two things, your code should end up looking more like this:
import { doc, updateDoc, deleteField } from "firebase/firestore";
const userDocRef = doc(this.firestore, 'users/' + uid);
await updateDoc(userDocRef, {
"profile.options.y": deleteField()
});
Your other option is to simply re-write the entire document using setDoc
, omitting the field that should not be present.
See also: