digitalCoffee
digitalCoffee

Reputation: 515

Delete a document from subcollection in Firestore with node.js

I'd like to remove a document from Firebase sub-collection. I'm trying to do this in the following way:

firestore.collection('categories').doc(categoryId).collection('books').doc(bookId).delete();

And it doesn't work.

However, I'm able to remove a document from the collection:

firestore.collection('categories').doc(categoryId).delete();

Am I losing sight of something? How should it work?

UPDATED:

const firebase = require('../firebase/firebaseAdmin');
const firestore = firebase.firestore();

module.exports = {
  removeBookFromCategory: (categoryId, bookId) => (
    firestore
      .collection('categories')
      .doc(categoryId)
      .collection('books')
      .doc(bookId)
      .delete()
  ),
};

I have correct ids here but I'm getting 500 error:

Error: Argument "documentPath" is not a valid ResourcePath. Path must be a non-empty string.

Upvotes: 8

Views: 6282

Answers (2)

Kesley Fortunato Alves
Kesley Fortunato Alves

Reputation: 141

I may be answering this too late, but i figured it out. If your database has the following scheme: rootCollection -> document -> subcollection -> documentInsideSubCollection

you can delete a document inside a subcollection using the snippet below:

  firestore.collection(rootCollection)
  .doc(documentName)
  .collection(subCollectionName).ref  
  .where(field, "==", something)
  .onSnapshot(snapshot => snapshot.forEach(result => result.ref.delete()));

Upvotes: 2

Sameera Sampath
Sameera Sampath

Reputation: 626

When you delete a document that has associated subcollections, the subcollections are not deleted. They are still accessible by reference. When you execute,

firestore.collection('categories').doc(categoryId).collection('books').doc(bookId).delete();

it will delete the document. But it won't delete subcollections. If you want to delete subcollections it has to be done manually. Please refer here

Upvotes: 7

Related Questions