Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 928
digitalCoffee Avatar asked Feb 09 '18 15:02

digitalCoffee


2 Answers

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

like image 126
Sameera Sampath Avatar answered Oct 16 '22 18:10

Sameera Sampath


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()));
like image 40
Kesley Fortunato Alves Avatar answered Oct 16 '22 18:10

Kesley Fortunato Alves