我是Firebase / Firestore的新手,并尝试创建一个Firebase功能,删除Auth帐户后会删除所有用户数据。
我的功能在删除帐户时被成功调用,我正在尝试删除该用户名为链接的集合,然后删除该用户文档。但是我收到了一个错误的链接.Ref.forEach不是一个函数。
关于我如何进行级联删除的任何指导?
exports.deleteUserData = functions.auth.user().onDelete((event) => {
const userId = event.data.uid;
const store = admin.firestore();
store.collection('users').doc(userId).get().then(user => {
if (user.exists) {
user.collection('links').get().then(links => {
links.forEach(link => {
link.delete();
})
return;
}).catch(reason => {
console.log(reason);
});
user.delete();
return;
}
else {
// User does not exist
return;
}
}
).catch(reason => {
console.log(reason);
});
});
答案 0 :(得分:2)
根据@Doug Stevenson关于Promises的评论,我设法通过拼凑代码来实现这一点。绝对不是最干净的,但如果有人试图做类似的话,它就有效。
// Delete user data when user deleted
exports.deleteUserData = functions.auth.user().onDelete((event) => {
const userId = event.data.uid;
const database = admin.firestore();
const linksRef = database.collection('users').doc(userId).collection('links');
const deleteLinks = deleteCollection(database, linksRef, BATCH_SIZE)
return Promise.all([deleteLinks]).then(() => {
return database.collection('users').doc(userId).delete();
});
});
/**
* Delete a collection, in batches of batchSize. Note that this does
* not recursively delete subcollections of documents in the collection
*/
function deleteCollection (db, collectionRef, batchSize) {
var query = collectionRef.orderBy('__name__').limit(batchSize)
return new Promise(function (resolve, reject) {
deleteQueryBatch(db, query, batchSize, resolve, reject)
})
}
function deleteQueryBatch (db, query, batchSize, resolve, reject) {
query.get()
.then((snapshot) => {
// When there are no documents left, we are done
if (snapshot.size === 0) {
return 0
}
// Delete documents in a batch
var batch = db.batch()
snapshot.docs.forEach(function (doc) {
batch.delete(doc.ref)
})
return batch.commit().then(function () {
return snapshot.size
})
}).then(function (numDeleted) {
if (numDeleted <= batchSize) {
resolve()
return
}
else {
// Recurse on the next process tick, to avoid
// exploding the stack.
return process.nextTick(function () {
deleteQueryBatch(db, query, batchSize, resolve, reject)
})
}
})
.catch(reject)
}
答案 1 :(得分:0)
基于Firebase的this official doc,似乎很容易设置clearData
函数。
它仅支持基本的Firestore结构。但是,在您的情况下,它应该只能通过以下方式配置user_privacy.json
:
{
"firestore": {
"clearData": [
{"collection": "users", "doc": "UID_VARIABLE", "field": "links"},
{"collection": "users", "doc": "UID_VARIABLE"}
],
}
}
对于更复杂的情况,需要对功能代码进行调整。
请参阅the doc