Reputation: 116
I'm using FieldValue.delete() to remove a field from a map instide a firestore document, but the key is still on the map. I want to remove the key, not just set an empty object as the value.
// Get the FieldValue object
var FieldValue = require('firebase-admin').firestore.FieldValue;
// Create a document reference
var exampleDocRef = db.collection('myDocumentType').doc('exampleDoc');
// Remove the key value pair from the map
var removeKeyValuePairInMap = exampleDocRef.update({
myMap:{ myKey:FieldValue.delete()}
});
Upvotes: 3
Views: 4913
Reputation: 1
For firebase v9+, this works for me
import { deleteField, updateDoc, doc } from 'firebase/firestore';
updateDoc(doc(db, 'my-collection', 'item-id'), {
myField: deleteField(),
});
Upvotes: 0
Reputation: 787
This is how you would do it in the client/browser
firebase.firestore().collection('yourCollection').doc('docID').update({
"objOne.ObjTwoIfItExists": firebase.firestore.FieldValue.delete()
})
This is how you would do it in a cloud function
admin.collection('yourCollection').doc('docID').update({
"objOne.ObjTwoIfItExists": admin.firestore.FieldValue.delete()
})
Using dot notation in the key allows you to access nested objects.
Upvotes: 2
Reputation: 11
i was facing the same problem as this. In my case, the variable i used for the object key was not actually used. But somehow the data from that variable was still extracted. Honestly i'm not even sure what went on. But this works for me.
To use a variable as key inside an object just use the square brackets.
// Firestore document
exampleDoc ={
id001: someData,
id002: someOtherData,
id003: someOtherOtherData,
}
// Get the FieldValue object
var FieldValue = require('firebase-admin').firestore.FieldValue;
// Create a document reference
var exampleDocRef = db.collection('myDocumentType').doc('exampleDoc');
// Create a variable to use as object key for the field u want to delete
var fieldToDelete = 'id001'
// Remove field from firestore (key & value)
var removeKeyValuePairInMap = exampleDocRef.update({
[fieldToDelete]: FieldValue.delete()
});
Upvotes: 1
Reputation: 31
One way to delete a key/value pair is to run a get() on the exampleDocRef and then delete it like you would any regular object's key/value pair and then update the doc after the deletion.
exampleDocRef.get().then(doc => {
const data = doc.data().myMap //gets it into something you can traverse
with dot notation
delete data[myKey]; //deletes key/value pair
exampleDocRef.update({ myMap: data}) //now just updating myMap with
itself minus the key/value pair you deleted
});
Ok, an edit to my previous answer above, here's a better way using your variables:
exampleDocRef.update({
myMap.myKey: FieldValue.delete()
})
You just have to make sure you traverse down to the key you want to delete with dot notation and call the delete() method. This deletes both key and value from the object.
Upvotes: 3