[英]How to delete a document in Firestore using cloud functions
我想检查在 firestore 中创建的文档,以确保公开可见的字段中没有包含脏话。 我希望能够在检测到包含脏话后删除该帖子。 为此,我正在尝试使用 firebase 云功能:
// Package used to filter profanity
const badWordsFilter = require('bad words-list');
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
export const filterBadWords =
functions.firestore.document("posts/{userId}/userPosts/{postId}").onCreate((snapshot, context) => {
const message = snapshot.data.val();
// Check if post contains bad word
if (containsSwearwords(message)) {
//This is where I want to remove the post.
//What do I put here to delete the document?
}
})
// Returns true if the string contains swearwords.
function containsSwearwords(message: any) {
return message !== badWordsFilter.clean(message);
}
数据库结构:
-posts(Collection)
|
+---{userID} (Document)
|
+---userPosts (collection)
|
+---{Documents to be checked} (Document)
|
+-Url1(field)
+-Url2(field)
+-string1(field)<- check this field for swear
+-string2(field)<- check this field for swear
云函数是使用 javascript 编写的
您可以使用ref
来获取DocumentReference
并调用delete()
:
functions.firestore.document("posts/{userId}/userPosts/{postId}").onCreate(
async (snapshot, context) => {
const message = snapshot.data.val();
// Check if post contains bad word
if (containsSwearwords(message)) {
await snapshot.ref.delete();
}
}
)
如果他们之后可以编辑他们的帖子,您应该概括此功能并将其添加到onUpdate
触发器中
这个答案会很简短,但不需要解释。 这是代码(对于 swift,我不是 100% 确定如何在 js 中执行此操作)
迅速:
db.collection("cities").document("DC").delete() { err in
if let err = err {
print("Error removing document: \(err)")
} else {
print("Document successfully removed!")
}
}
这可能适用于 javascript,而不是 100% 确定
db.collection("cities").doc("DC").delete().then(function() {
console.log("Document successfully deleted!");
}).catch(function(error) {
console.error("Error removing document: ", error);
});
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.