Search code examples
javascriptnode.jsexpressrestobjectid

Argument passed in must be a single String of 12 bytes or a string of 24 hex characters?


enter image description here''' This is my endpoint to delete the task but due to some problem it's not working when i try from postman. When I enter the ID through hard code(statically) its working. '''

router.delete('/tasks/:id', async (req, res) => { try {

    const task = await Task.findByIdAndDelete(req.params.id) //[![Why my objectid is not valid. It's working fine for other routes ][1]]
    if (!task) {
        res.status(404).send()
    }

    res.send(task)
} catch (e) {
    res.status(500).send()
}

})


Solution

  • use trim method available on strings in javascript you are getting an extra '\n' character at the end of your objectId.

    const {id} = req.params; // destructuring in javascript
     const task = await Task.findByIdAndDelete(id.trim()) // trim the string 
        if (!task) {
            res.status(404).send()
        }
        res.send(task)
    } catch (e) {
        res.status(500).send()
    }