Delete the old documents that i already copy

I’m trying to pass the documents that i have in a collection to another one, i already copy the documents in the old collection to the new one but now i dont know how to delete the old documents

For now i have this:

FirebaseFirestore.instance
          .collection('users')
          .doc(user.uid)
          .collection('shoplist')
          .get()
          .then((querySnapshot) => {
                querySnapshot.docs.forEach((result) {
                  FirebaseFirestore.instance
                      .collection('users')
                      .doc(user.uid)
                      .collection('history')
                      .doc()
                      .set(result.data())
                      .then((value) => querySnapshot.docs.delete()); // Here is where i don't know what to do
                })
              });

>Solution :

You’re trying to delete all documents in the QuerySnapshot in one call, which isn’t possible. Instead, you should delete each document after you’ve written the copy, with:

  FirebaseFirestore.instance
      .collection('users')
      .doc(user.uid)
      .collection('history')
      .doc()
      .set(result.data())
      .then((value) => result.reference.delete()); // 👈

Also note that you’re current losing the original document ID in your copy. If your document IDs are meaningful, you want to maintain the document ID in the copy, and you only have one copy of each document, use:

  FirebaseFirestore.instance
      .collection('users')
      .doc(user.uid)
      .collection('history')
      .doc(result.id) // 👈
      .set(result.data())
      .then((value) => result.reference.delete());

Leave a Reply