Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all the documents in a firestore collection database

I use Firestore database to store and retrieve data. Every night there need to be fresh data set (documents)available in the Firestore collection. So is there any way to fully delete all the existing documents inside a collection at once.

I tried there documentation and it says we need to delete one by one which is impossible to do. Because document ID is generating automatically.

Below is the code from documantaion.

var cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
    capital: firebase.firestore.FieldValue.delete()
});

So is there any way to delete entire documents on a given fire base collection?

I tried with above code and I got below error.

(index):63 Uncaught ReferenceError: Firestore is not defined
    at myFunction ((index):63)
    at HTMLParagraphElement.onclick ((index):57)

Below is my code:

<p id="demo" onclick="myFunction()">Click me.</p>

<script>


function myFunction() {

describe("firestore", () => {
    var db;
    before(() => {
        var config = {
            apiKey: "xxxx",
            aauthDomain: "xxxxfirebaseapp.com",
            projectId: "xxx",
        };
        var app = firebase.initializeApp(config);
        db = firebase.firestore(app);
        //firebase.firestore.setLogLevel("debug");
    });


db.collection('Headings').get().then(querySnapshot => {
    querySnapshot.docs.forEach(snapshot => {
        snapshot.ref.delete();
    })
})
}
</script>
like image 248
user2728409 Avatar asked Oct 27 '25 08:10

user2728409


1 Answers

The documentation is correct: you have to delete the documents individually. It's not impossible - you just have to query for all the documents first, then delete each one. For example:

db.collection('cities').get().then(querySnapshot => {
    querySnapshot.docs.forEach(snapshot => {
        snapshot.ref.delete();
    })
})
like image 75
Doug Stevenson Avatar answered Oct 28 '25 20:10

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!