【问题标题】:Get error "doc.delete" is not a function when trying to delete docs in a Firestore CollectionGroup [duplicate]尝试删除 Firestore CollectionGroup 中的文档时出现错误“doc.delete”不是函数 [重复]
【发布时间】:2021-08-30 10:23:57
【问题描述】:

我有一个应用程序,用户可以在其中创建帖子。用户还可以为这些帖子添加书签。但是,当帖子作者删除其他人可能已添加书签的帖子时,我还需要自动删除与已删除帖子关联的那些书签。

这是我的数据模型(当用户为帖子添加书签时,书签会保存到名为 bookmarks 的子集合中的用户记录中:

我已经编写了删除书签的代码逻辑,如下所示:

          const postsQuery = await this.$fire.firestore
            .collectionGroup('bookmarks')
            .where('id', '==', this.post.id)
            .get()
          postsQuery.forEach((doc) => doc.delete())
          console.log('bookmark deleted')
        } catch (error) {
          console.error('error deleteing post.', error)
        }

问题:尝试删除书签时出现以下控制台错误:

EditPost.vue?4144:107 error deleteing post. TypeError: doc.delete is not a function
    at eval (EditPost.vue?4144:95)
    at eval (prebuilt-28889c43-f8ea673b.js?f270:18228)
    at eval (prebuilt-28889c43-f8ea673b.js?f270:16453)
    at eval (prebuilt-28889c43-f8ea673b.js?f270:11563)
    at t.inorderTraversal (prebuilt-28889c43-f8ea673b.js?f270:2801)
    at t.inorderTraversal (prebuilt-28889c43-f8ea673b.js?f270:2719)
    at t.forEach (prebuilt-28889c43-f8ea673b.js?f270:11562)
    at t.forEach (prebuilt-28889c43-f8ea673b.js?f270:16452)
    at t.forEach (prebuilt-28889c43-f8ea673b.js?f270:18227)
    at _callee$ (EditPost.vue?4144:94)

如何正确编写此删除逻辑?谢谢!

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore


    【解决方案1】:

    doc.delete 不是函数

    这是因为doc 是QueryDocumentSnapshot 而不是DocumentReference。你需要使用ref属性如下:

    const postsQuery = await this.$fire.firestore
            .collectionGroup('bookmarks')
            .where('id', '==', this.post.id)
            .get()
    postsQuery.forEach((doc) => doc.ref.delete())
    

    请注意,如果您想监控何时删除所有书签 (console.log('bookmark deleted')),您可以使用 batched write(在您的情况下是批量删除!)或 Promise.all()

    【讨论】:

    • 感谢您对批量写入的评论。我让它部分工作,但我将提交另一个问题,因为我不确定如何在使用循环时添加批量写入。
    • @redshift 当然,当你发布新问题时告诉我,我会很高兴地回答! :-)
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    相关资源
    最近更新 更多