Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading