Error handling in js Node

Asked

Viewed 1,551 times

1

I’m doing an error treatment that if a wrong id is passed by url he returns a error 400, but when I take the test it returns a error 200 one more message

"error": "Error", "message": "Cast to ObjectId failed for value \"5d69f4aa827b491c678c50a\" at path \"_id\" for model \"Product\""

Follow the controller:

router.get('/product-view/:id', async (req, res) => {    
    const id = req.params.id    
    try{    
        if(!id) return res.status(404).send({ error: 'Produto não encontrado'})    
        console.log(id);        
        const product = await Product.findById(id);        
        res.send(product);        

    }catch(error){    
       res.send({    
            error: 'Error',
            message: error.message    
       })    
    }       
});
  • Product.findById apparently the error is here ... you use which database?

  • I use Mongo DB

  • Status 200 is not error, but success, you need to call the method status with the return code. Ex. res.status(400).send({error: 'Error', message: error.message})

1 answer

1

Problem: the id recovered is a different type than the method findById understands, in this case this method needs a Objectid (mongoose.Schema.Types.ObjectId) to fetch information from the bank , or an object with the following structure {_id: id} or a string with the name _id, as described in its documentation.

Particularly speaking I prefer to always put a guy who in the case is Objectid, example:

router.get('/product-view/:id', async (req, res) => {    
    const id = req.params.id    
    try{    
        if(!id) return res.status(404).send({ error: 'Produto não encontrado'})    
        const _id = new ObjectId(id);  // instância requerida pelo seu código
        const product = await Product.findById({_id:_id}); // ou simplificando {_id}        
        res.send(product);        

    }catch(error){    
       res.send({    
            error: 'Error',
            message: error.message    
       })    
    }       
});

and this guy Objectid is mongoose.Types.ObjectId which is the type of data recorded in your .

or quick fix in your code:

router.get('/product-view/:id', async (req, res) => {    
    const id = req.params.id    
    try{    
        if(!id) return res.status(404).send({ error: 'Produto não encontrado'})      
        const product = await Product.findById({_id: id});        
        res.send(product);        

    }catch(error){    
       res.send({    
            error: 'Error',
            message: error.message    
       })    
    }       
});

Referent:

Examples

  • So I used the first example that Voce put but this giving this error : Objectid is not defined

  • You need to take the full path, there is no error in my code, and you need to put the correct reference, if it is difficult make the second option, the two are correct @Edgarsilva

Browser other questions tagged

You are not signed in. Login or sign up in order to post.