删除另一个文档 firebase firestore 后删除文档-react-web

时间:2021-02-23 09:27:00

标签: reactjs google-cloud-firestore

我想删除一个文档,然后在下一个 .then() 方法中删除另一个 虽然我不确定如何将值传递给下一个 .then() 方法?

exports.deleteJobPost = (req,res) => {
               
    const document = db.collection("users").doc(req.user.username).collection("MyJobPosts").doc(req.params.jobPostId)

    document.get().then(doc => {

        if(!doc.exists){
            return res.status(404).json({error: "Job Post Not Found"})
        }


        if(doc.data().username !== req.user.username){
            //403 Forbidden
            return res.status(403).json({error: "unauthorised"})
        } else {
             
             const state = doc.data().state
             const  category = "electrical"

             console.log("this is state and category: " + state + " " + category)
             const secondDocument = db.collection("JobPosts").doc(state).collection(category).doc(req.params.jobPostId);
             return document.delete(),secondDocument.delete;
        }
    })
    .then(() => {
        res.json({message: `Job Post Deleted Successfully`}) 
    })
}

1 个答案:

答案 0 :(得分:1)

您当前的代码不需要最后一个 then(),但在删除第一个文档后确实需要一个,下面的代码应该足以满足您的要求:

exports.deleteJobPost = (req,res) => {
               
    const document = db.collection("users").doc(req.user.username).collection("MyJobPosts").doc(req.params.jobPostId)

    document.get().then(doc => {

        if(!doc.exists){
            return res.status(404).json({error: "Job Post Not Found"})
        }


        if(doc.data().username !== req.user.username){
            //403 Forbidden
            return res.status(403).json({error: "unauthorised"})
        } else {
             
             const state = doc.data().state
             const  category = "electrical"

             console.log("this is state and category: " + state + " " + category)
             const secondDocument = db.collection("JobPosts").doc(state).collection(category).doc(req.params.jobPostId);
             document.delete().then(() => {
                 secondDocument.delete().then(() => {
                     res.json({message: `Job Post Deleted Successfully`}) ;
                 });
             });
        }
    })
}
相关问题