How to check if an object has been already created?

Viewed 36

Hello i would like to check if an object was created. If its created then redirect to the id page but if it isnt created redirect to the page where its being created.

Here is my app

app.get('/my',isLoggedIn,async (req,res)=> {
    const safe= await Safe.find({});
    if(safe===undefined){
        res.redirect('/mysafe')
    }
    else {
         res.redirect(`mysafe/${safe._id}`)
    }
})

i think it should work but im getting a cast error CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Safe"

1 Answers

You just need to flip your conditional and use if(safe) as the condition. That will be true if the object has been created and false if not. Something along the lines of:

app.get('/my', isLoggedIn, async (req,res) => {
    const safe= await Safe.find({});
    if(safe){
        res.redirect(`mysafe/${safe._id}`)
    } else {
        res.redirect('/mysafe')
    }
})

Related