Home > other >  How to check if an object has been already created?
How to check if an object has been already created?

Time:11-12

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}`)
    }
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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"

CodePudding user response:

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')
    }
})
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related