如何从auth.user.onDelete触发器删除文档集合和所有嵌套数据

时间:2020-03-22 23:28:27

标签: firebase google-cloud-firestore google-cloud-functions

当前,删除用户数据的逻辑如下:

import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';

const firestore_tools = require('firebase-tools');

admin.initializeApp();

const Auth = admin.auth();
const UsersCollection = admin.firestore().collection(`users`);

exports.deleteUserDocuments = functions.auth.user().onDelete((user) => {
  const userID = user.uid;

  UsersCollection.doc(userID)
      .delete({})
      .catch(error => {
        return error
      });
});

但是由于用户文档记录包含嵌套的集合,这些嵌套的集合包含其他文档和集合,因此由于以下事实,它们仍被保留: When you delete a document, Cloud Firestore does not automatically delete the documents within its sub-collections

我研究了一下,找到了有关如何创建可调用函数的文档: https://firebase.google.com/docs/firestore/solutions/delete-collections

但是我想知道是否有可能通过auth.user.onDelete触发器执行此逻辑吗?

使用解决方案更新

const firestore_tools = require('firebase-tools');

exports.deleteUserDocuments = functions.auth.user().onDelete((user) => {
    const userID = user.uid;
    const project = process.env.GCLOUD_PROJECT;
    const token = functions.config().ci_token;
    const path = `/users/${userID}`;

    console.log(`User ${userID} has requested to delete path ${path}`);

    return firestore_tools.firestore
        .delete(path, {
            project,
            token,
            recursive: true,
            yes: true,
        })
        .then(() => {
            console.log(`User data with ${userID} was deleted`);
        })
});

1 个答案:

答案 0 :(得分:1)

您可以在所需的任何触发器中运行所需的任何代码。触发器的类型与您可以运行的代码类型无关。