如何使用云功能从 Firestore 中删除数据

How to delete data from Firestore with cloud functions

我正在结合 google 的 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

答案是必须写一个云函数,自己删除数据,由客户端触发。没有一种有效的方法可以在客户端进行。我使用的方法是先在云函数中监听删除,然后触发递归。

要在节点 js 中删除的代码:

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

可以使用下面的代码递归删除集合中的所有文档。
这段代码非常适合我。
确保安装了 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);
    });
}