Home > database >  How do I delete a document from Firebase 9 js using a query?
How do I delete a document from Firebase 9 js using a query?

Time:10-05

I want to delete a doc from 'albums' collection, but only the one, which name property matches props.album.name. I would expect this code to work:

  const colRef = collection(firestore, 'albums')
  const q = query(colRef, where('name', '==', props.album.name))
  const querySnapshot = await getDocs(q)
  querySnapshot.forEach(doc => {
    deleteDoc(doc)
  })

but I get an error instead:

Uncaught (in promise) TypeError: right-hand side of 'in' should be an object, got undefined

What am I doing wrong?

CodePudding user response:

Since you're looping over a QuerySnapshot each doc object is a QueryDocumentSnapshot, while deleteDoc expects a DocumentReference. To get from the former to the latter, you can call .ref on the snapshot.

So:

querySnapshot.forEach(doc => {
  deleteDoc(doc.ref)
})
  • Related