【发布时间】:2021-08-31 12:40:32
【问题描述】:
我正在学习 Firestore 的 batch writes 方法,它看起来非常简洁。几乎是异步的!但是,我需要一些帮助来弄清楚在查询上执行 forEach() 时如何运行批处理语句。
我的用例是,当用户删除帖子时,我还需要“清理”并更新/删除与该帖子关联的其他项目。这可能是用户为此帖子创建的所有书签、点赞等。
这是deletePost 函数的示例。 如何对bookmarksQuery 和usersAnswerQuery 查询运行批处理语句?
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
}
}
【问题讨论】:
标签: firebase vue.js google-cloud-firestore nuxt.js