gpt4 book ai didi

angular - 如何在 angularfire firestore 中删除整个文档集合

转载 作者:行者123 更新时间:2023-12-05 07:35:29 27 4
gpt4 key购买 nike

我刚刚更改了我的代码如下,它正在运行。可以在 google cloud-firestore 中批量删除。

async deleteMembersOfGroup(clubId: string, groupId: string) {
//path of the collection
const path = "club/" + clubId + "/group/" + groupId + "/group-members";

//query snapshot
const qry: firebase.firestore.QuerySnapshot = await this.afs.collection(path).ref.get();

const batch = this.afs.firestore.batch();

//looping through docs in the collection to delete docs as a bulk operation
qry.forEach(doc => {
console.log('deleting....', doc.id);
batch.delete(doc.ref);
});

//finally commit
batch.commit().then(res => console.log('committed batch.'))
.catch(err => console.error('error committing batch.', err));
}

最佳答案

docs说:

Deleting collections from a Web client is not recommended.

因此省略了示例(尽管提供了 Node.js 示例)。

因此,您可以调整 Node.js 代码以在 JavaScript 中工作(尽管 Google 不推荐这样做),或者您可以使用 Google 提供的云函数解决方案(如果您使用的是云函数)。

Delete collection with a Callable Cloud Function

这是直接来自文档的云函数代码:

云函数代码

/**
* Initiate a recursive delete of documents at a given path.
*
* The calling user must be authenticated and have the custom "admin" attribute
* set to true on the auth token.
*
* This delete is NOT an atomic operation and it's possible
* that it may fail after only deleting some documents.
*
* @param {string} data.path the document or collection path to delete.
*/
exports.recursiveDelete = functions
.runWith({
timeoutSeconds: 540,
memory: '2GB'
})
.https.onCall(async (data, context) => {
// Only allow admin users to execute this function.
if (!(context.auth && context.auth.token && context.auth.token.admin)) {
throw new functions.https.HttpsError(
'permission-denied',
'Must be an administrative user to initiate delete.'
);
}

const path = data.path;
console.log(
`User ${context.auth.uid} has requested to delete path ${path}`
);

// Run a recursive delete on the given document or collection path.
// The 'token' must be set in the functions config, and can be generated
// at the command line by running 'firebase login:ci'.
await firebase_tools.firestore
.delete(path, {
project: process.env.GCLOUD_PROJECT,
recursive: true,
force: true,
token: functions.config().fb.token
});

return {
path: path
};
});

客户端代码

/**
* Call the 'recursiveDelete' callable function with a path to initiate
* a server-side delete.
*/
function deleteAtPath(path) {
var deleteFn = firebase.functions().httpsCallable('recursiveDelete');
deleteFn({ path: path })
.then(function(result) {
logMessage('Delete success: ' + JSON.stringify(result));
})
.catch(function(err) {
logMessage('Delete failed, see console,');
console.warn(err);
});
}

一如既往,为什么GCP这么难!

关于angular - 如何在 angularfire firestore 中删除整个文档集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49531458/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com