I am learning about Firestore's batch writes method and it looks really neat. Almost async-like! However, I am needing some help figuring out how to run a batch statement when doing a forEach()
on a query.
My use case is that when a user deletes a post, I need to also "clean up" and update/delete other items associated with that post. That could be all bookmarks users have created for this post, likes, etc.
Here is an example of a deletePost
function. How do you run a batch statement on the bookmarksQuery
and usersAnswerQuery
queries?
async deletePost(post) {
const response = confirm('Delete this post?')
const batch = this.$fire.firestore.batch()
if (response === true && this.userProfile.uid === this.post.uid) {
try {
const postRef = this.$fire.firestore
.collection(`users/${post.uid}/posts`)
.doc(this.post.id)
const answerRef = this.$fire.firestore
.collection('answers')
.doc(this.post.commentIdWithAnswer)
const usersAnswerQuery = await this.$fire.firestore
.collectionGroup('answers')
.where('id', '==', this.post.commentIdWithAnswer)
.get()
const bookmarksQuery = await this.$fire.firestore
.collectionGroup('bookmarks')
.where('id', '==', this.post.id)
.get()
batch.update(postRef, {
published: false,
deleted: true,
updatedAt: this.$fireModule.firestore.FieldValue.serverTimestamp()
})
bookmarksQuery.forEach((doc) => doc.ref.delete()) //<---- how to add this to batch?
usersAnswerQuery.forEach((doc) => doc.ref.delete()) //<---- how to add this to batch?
batch.delete(answerRef)
await batch.commit()
// To do: delete all user 'likes' associated with this post
alert('Post successfully deleted!')
} catch (error) {
console.error('error deleting post.', error)
}
} else {
return null
}
}