【问题标题】:How to delete all the documents in a firestore collection database如何删除firestore集合数据库中的所有文档
【发布时间】:2020-09-17 07:27:06
【问题描述】:

我使用 Firestore 数据库来存储和检索数据。 每天晚上,Firestore 集合中都需要有可用的新数据集(文档)。 那么有没有办法一次完全删除集合中的所有现有文档。

我试过那里的文档,它说我们需要一个一个地删除,这是不可能的。 因为文档 ID 是自动生成的。

以下是来自documantaion的代码。

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

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

那么有什么方法可以删除给定火库集合中的整个文档?

我尝试使用上面的代码,但出现以下错误。

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

下面是我的代码:

<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>

【问题讨论】:

    标签: javascript google-cloud-firestore


    【解决方案1】:

    文档是正确的:您必须单独删除文档。这不是不可能的——你只需要query for all the documents first,然后delete each one。例如:

    db.collection('cities').get().then(querySnapshot => {
        querySnapshot.docs.forEach(snapshot => {
            snapshot.ref.delete();
        })
    })
    

    【讨论】:

    • 感谢您的快速回复。是否有可能获得完整的 JavaScript 代码。我对此有点陌生,为此苦苦挣扎了几个小时。
    • 这是整个 JavaScript 代码,源自您最初展示的内容。随意调整它以满足您的特定需求。
    • 你的答案是正确的。我唯一需要修改的是:var db = firebase.firestore();
    猜你喜欢
    • 2020-09-08
    • 2018-11-01
    • 2018-10-19
    • 1970-01-01
    • 2023-03-24
    • 2021-01-08
    • 2019-04-04
    相关资源
    最近更新 更多