benpalmer
benpalmer

Reputation: 383

delete document after deleting another document firebase firestore - react - web

I'm looking to delete one document then delete another in the next .then() method though i am unsure how to pass the values down to the next .then() method?

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`}) 
    })
}

Upvotes: 2

Views: 58

Answers (1)

Rafael Lemos
Rafael Lemos

Reputation: 5819

You don't need that last then() on your current code, but you do need one following the deletion of the first document, the code below should be enough for what you are trying to achieve:

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`}) ;
                 });
             });
        }
    })
}

Upvotes: 1

Related Questions