简体   繁体   中英

Delete item from subcollection array in Firestore Firebase

I am trying to delete item from array in profile collection named items subcollection. Function should be triggered whenever item is deleted from main items collection. Problem with below function is that when triggered it deletes all items from profile instead of deleted one only. How I could iterate over items array and perform check of deleted item id.

 exports.updateDeletedItemOnProfile = functions.firestore.document('items/{itemId}').onDelete((snap, context) => { const { itemId } = context.params const deletedItem = snap.data() if(deletedItem){ db.collection('profiles').doc(deletedItem.user.id).update({ items: admin.firestore.FieldValue.delete({ id: itemId, title: deletedItem.title, price: deletedItem.price, image: deletedItem.image }) }) } return true })

onDelete triggers only fire when an entire document was deleted. By this time, it's too late - the document is simply gone. Something chose to delete it, and you won't be able to tell what did that.

If you want a function to trigger when any part of a document is modified, you should use an onUpdate trigger instead. That will give you the entire contents of the document before and after the change. You will have to compare them to figure out what specifically changed.

I 've also tried onUpdate trigger for deleting data along with onWrite trigger to listen for any change when data is changed, however in both cases it does not give me any result for part referring to deleting data. Items subcollection in profiles collection remains unchanged. I am not sure where error in function lies, function execution does not show any error, finishes with status Ok....

 exports.updateDeletedItemOnProfile = functions.firestore.document('items/{itemId}').onUpdate((change, context) => { const { itemId } = context.params const beforeItem = change.before.data() const updatedItem = change.after.data() if (updatedItem === null) { return db.collection('profiles').doc(beforeItem.user.id).delete({ items: admin.firestore.FieldValue.arrayRemove({ id: itemId, title: beforeItem.title, price: beforeItem.price, image: beforeItem.image, status: beforeItem.status, }) }) } return true })

 exports.updateDeletedItemOnProfile = functions.firestore.document('items/{itemId}').onUpdate((change, context) => { const { itemId } = context.params const beforeItem = change.before.data() const updatedItem = change.after.data() if (updatedItem === null) { return db.collection('profiles').doc(beforeItem.user.id).update({ items: admin.firestore.FieldValue.delete({ id: itemId, title: beforeItem.title, price: beforeItem.price, image: beforeItem.image, status: beforeItem.status, }) }) } return true })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM