[英]Delete multiple documents with firebase cloud function
Sorry for the rookie question, but I am about to toss my laptop.很抱歉这个菜鸟问题,但我正要扔掉我的笔记本电脑。
I'm new to js and have been struggling to understand how to use promises.我是 js 的新手,一直在努力理解如何使用 Promise。
When a conversation is deleted this function is triggered and should loop throw all the messages contained in the conversation and delete them.当一个对话被删除时,这个函数被触发并且应该循环抛出对话中包含的所有消息并删除它们。
My problem is I don't no where to delete the messages or how to do it.我的问题是我不知道在哪里删除消息或如何做。 How do I delete the messages?如何删除消息?
exports.deleteMessages = functions.firestore
.document('users/{userId}/conversations/{conversationId}')
.onDelete(event => {
// Get an object representing the document prior to deletion
const deletedConversation = event.data.previous.data();
return database.collection('messages')
.where('conversationId', '==', deletedConversation.id).get()
.then(snapshot => {
snapshot.forEach(document => {
const data = document.data();
database.collection('messages').document(data.id).delete();
});
return console.log("Don't even no why I'm returning this")
})
.catch(error => {
console.log('Error when getting document ' + error)
});
});
You have to use Promise.all(), which "returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises."您必须使用 Promise.all(),它“返回一个 Promise,当 iterable 参数中的所有承诺都已解决或当 iterable 参数不包含任何承诺时,该承诺已解决。”
You should do along these lines:您应该按照以下方式进行:
const promises = [];
return database.collection('messages')
.where('conversationId', '==', deletedConversation.id).get()
.then(snapshot => {
snapshot.forEach(document => {
//Create a Promise that deletes this document
//Push the Promise in the "promises" array
promises.push(deleteDocPromise(document))
});
//and return:
return Promise.all(promises);
})
.then(
//Do whatever you want in case of succesfull deletion of all the doc
)
.catch(error => {
....
});
In order to create the Promise for deletion do something like为了创建删除的承诺,请执行以下操作
function deleteDocPromise(document) {
//using the code of your question here
const data = document.data();
return database.collection('messages').doc(data.id).delete();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.