【问题标题】:How to delete data from Firestore with cloud functions如何使用云功能从 Firestore 中删除数据
【发布时间】:2018-04-23 05:33:11
【问题描述】:

我正在结合谷歌的 Firestore 数据库编写云函数。

我正在尝试编写递归删除更多数据。我在数据库的其他部分找不到访问和删除数据的语法。 我已经拥有的代码如下。

exports.deleteProject = functions.firestore.document('{userID}/projects/easy/{projectID}').onDelete(event => {
    // Get an object representing the document prior to deletion
    // e.g. {'name': 'Marie', 'age': 66}
    // console.log(event)
    // console.log(event.data)
    console.log(event.data.previous.data())

    var deletedValue = event.data.previous.data();

});

我在这里找到了一些信息,但我没有时间在 atm 上检查它,如果我发现有用的东西我会修改问题。

https://firebase.google.com/docs/firestore/manage-data/delete-data?authuser=0

【问题讨论】:

    标签: node.js google-cloud-platform google-cloud-firestore


    【解决方案1】:

    可以使用以下代码递归删除集合中的所有文档。
    这段代码非常适合我。
    确保您已安装 JSON 文件的 firebase credentialsfirebase-admin

    const admin = require('firebase-admin');
    const db = admin.firestore();
    const serviceAccount = require('./PATH_TO_FIREBASE_CREDENTIALS.json');
    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount)
    });
    
    deleteCollection(db, COLLECTION_NAME, NUMBER_OF_RECORDS)
    async function deleteCollection(db, collectionPath, batchSize) {
        const collectionRef = db.collection(collectionPath);
        const query = collectionRef.orderBy('__name__').limit(batchSize);
    
        return new Promise((resolve, reject) => {
            deleteQueryBatch(db, query, resolve).catch(reject);
        });
    }
    
    async function deleteQueryBatch(db, query, resolve) {
        const snapshot = await query.get();
    
        const batchSize = snapshot.size;
        if (batchSize === 0) {
            // When there are no documents left, we are done
            resolve();
            return;
        }
    
        // Delete documents in a batch
        const batch = db.batch();
        snapshot.docs.forEach((doc) => {
            batch.delete(doc.ref);
        });
        await batch.commit();
    
        // Recurse on the next process tick, to avoid
        // exploding the stack.
        process.nextTick(() => {
            deleteQueryBatch(db, query, resolve);
        });
    }    
    

    【讨论】:

      【解决方案2】:

      答案是你必须编写一个云函数,它自己删除数据并由客户端触发。在客户端没有有效的方法来做到这一点。我使用的方法是在云函数中监听第一次删除,然后触发递归。

      节点js中要删除的代码:

      db.collection("cities").document("DC").delete(
      

      【讨论】:

      • 如果这是一个糟糕的解决方案,有人可以指出一个更好的解决方案吗?
      猜你喜欢
      • 2021-02-13
      • 2021-02-04
      • 2021-08-09
      • 2018-06-30
      • 2021-08-19
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多