0

I have an app where a user can create a post. Users can also bookmark these posts. However, when a post author deletes his post that others may have already bookmarked, I need to also automatically delete those bookmarks that are associated to the deleted post.

Here's my data model (when a user bookmarks a post, the bookmark is saved to the user's record in a subcollection called bookmarks:

enter image description here

I've written the code logic to delete a bookmark like so:

          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)
        }

Problem: I get the following console error when trying to delete the bookmark:

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)

How can I correctly write this delete logic? Thanks!

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
redshift
  • 4,815
  • 13
  • 75
  • 138

1 Answers1

1

doc.delete is not a function

This is because doc is a QueryDocumentSnapshot and not a DocumentReference. You need to use the ref property as follows:

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

Note that if you want to monitor when all the bookmarks are deleted (console.log('bookmark deleted')) you may use a batched write (a batched deletion in your case!) or Promise.all()

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • Thanks for your comment about batched write. I have it partially working, but I will submit another question as I am unsure how to add batch write when using loops. – redshift Jun 15 '21 at 11:52
  • 1
    @redshift Sure, just tell me when you have posted the new question, I'll answer it with pleasure! :-) – Renaud Tarnec Jun 15 '21 at 13:30
  • Here ya go! https://stackoverflow.com/q/67990044/2420614 – redshift Jun 15 '21 at 16:23