I would like to be able to delete varToDelete field inside a map if a condition occurs.
For some reason, the code to delete it is reached, but nothing is happening
Here is the structure of my document:
loc [
{
var1,
var2,
varToDelete
},
{
var1,
var2,
varToDelete
}
]
So, I started to think about this code:
await db.runTransaction(async (t) => {
var locRef = db.collection('documents').doc('123-456');
var locSnapshot = await locRef.get();
var loc = locSnapshot.data().loc;
loc.forEach(l => {
if (typeof l.varToDelete !== 'undefined') {
t.update(locRef, {
"varToDelete": admin.firestore.FieldValue.delete()
});
}
});
});
"varToDelete": admin.firestore.FieldValue.delete()
This will delete a field 'varToDelete' in the document itself. There is not direct method to delete a field from maps in an array. You must read the doc, remove that property from the objects and update the document with the whole new 'loc' array.
const newArr = locSnapshot.data().loc.map(({varToDelete, ...rest}) => rest)
t.update(locRef, {loc: newArr})