使用admin SDK和callable cloud函数以与客户端SDK最相似的方式删除一批文档? &



我有一个文档id数组,我想在使用云函数时删除它,我的代码如下所示:

//If the user decieds on deleting his account forever we need to make sure we wont have any thing left inside of db after this !!
// incoming payload array of 3 docs
data = {array : ['a302-5e9c8ae97b3b','92c8d309-090d','a302-5e932c8ae97b3b']}
export const deleteClients = functions.https.onCall(async (data, context) => {
try {
// declare batch
const batch = db.batch();
// set
data.arr.forEach((doc: string) => {
batch.delete(db.collection('Data'), doc);
});
// commit 
await batch.commit();

} catch (e) {
console.log(e);
}
return null;
});
如何将正确的参数传递到批量删除以引用我想在提交之前提交删除的文档?

Delete接受一个参数,即要删除的文档的doc ref。

data.arr.forEach((docId: string) => {
batch.delete(doc(db, "Data", docId));
});

你的代码中有几个错误:

  • data.arr.forEach()不能工作,因为您的数据对象包含一个键为array的元素,而不是键为arr的元素。
  • 你混淆了JS SDK v9和Admin SDK的语法。请参阅此处的写批管理SDK语法。
  • 当所有异步工作完成时,您需要向客户端发回一些数据,以正确终止CF。
  • 你做return null;后的try/catch块:这意味着,在大多数情况下,你的云功能将在异步工作完成之前终止(见上面的链接)

所以下面的代码应该可以达到这个效果(未经测试):

const db = admin.firestore();
const data = {array : ['a302-5e9c8ae97b3b','92c8d309-090d','a302-5e932c8ae97b3b']};
export const deleteClients = functions.https.onCall(async (data, context) => {
try {

const batch = db.batch();
const parentCollection = db.collection('Data')

data.array.forEach((docId) => {   
batch.delete(parentCollection.doc(docId));
});
// commit 
await batch.commit();

return {result: 'success'} // IMPORTANT, see explanations above

} catch (e) {
console.log(e);
// IMPORTANT See https://firebase.google.com/docs/functions/callable#handle_errors
}

});

最新更新