【问题标题】:Delete multiple documents with firebase cloud function使用firebase云功能删除多个文档
【发布时间】:2018-03-27 14:04:56
【问题描述】:

很抱歉这个菜鸟问题,但我正要扔掉我的笔记本电脑。

我是 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)
        });
});

【问题讨论】:

    标签: javascript node.js firebase google-cloud-functions


    【解决方案1】:

    您必须使用 Promise.all(),它“返回单个 Promise,当可迭代参数中的所有承诺都已解决或可迭代参数不包含任何承诺时,该 Promise 将解决。”

    您应该遵循以下原则:

    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 => {
            ....
        });
    

    为了创建 Promise 以进行删除,请执行类似

    的操作
    function deleteDocPromise(document) {
            //using the code of your question here
            const data = document.data();
            return database.collection('messages').doc(data.id).delete();   
    }
    

    【讨论】:

    • 非常感谢!我的代码中存在类型错误,因此返回 database.collection('messages').document(data.id).delete();应该是 return database.collection('messages').doc(data.id).delete();,这是我的错,除此之外它按预期工作!
    • @user3116871 酷 :-) 我已经用 database.collection('messages').doc(data.id).delete(); 调整了响应;
    猜你喜欢
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多