![](/img/trans.png)
[英]How to do a Batch delete Firestore Documents in a Firebase cloud function
[英]Delete multiple documents with firebase cloud function
很抱歉这个菜鸟问题,但我正要扔掉我的笔记本电脑。
我是 js 的新手,一直在努力理解如何使用 Promise。
当一个对话被删除时,这个函数被触发并且应该循环抛出对话中包含的所有消息并删除它们。
我的问题是我不知道在哪里删除消息或如何做。 如何删除消息?
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)
});
});
您必须使用 Promise.all(),它“返回一个 Promise,当 iterable 参数中的所有承诺都已解决或当 iterable 参数不包含任何承诺时,该承诺已解决。”
您应该按照以下方式进行:
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 => {
....
});
为了创建删除的承诺,请执行以下操作
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.