Mongoose CastError (Cast to ObjectId failed)

Viewed 44

While testing my api routes in postman, I got this error "Cast to ObjectId failed for value "632aa0c8930ca0decc7d042b\n" (type string) at path "_id" for model "User"".

Here is the controller and route part of the update api:

// routes

app.put("/api/users/:id", authorization, UserController.updateUser);

// controller

updateUser: async (req, res) => {

    try {
        
        const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, {new:true, runValidators:true})

        res.status(200).json(updatedUser)

    } catch(err) {
        res.status(500).json(err)
    }
}

Here is the error shown in postman: { "stringValue": ""632aa0c8930ca0decc7d042b\n"",
"valueType": "string",
"kind": "ObjectId",
"value": "632aa0c8930ca0decc7d042b\n",
"path": "_id",
"reason": {},
"name": "CastError",
"message": "Cast to ObjectId failed for value "632aa0c8930ca0decc7d042b\n" (type string) at path "_id" for model "User"" }

What can go wrong? Any help would be appreciated

1 Answers

It says that; you try to findById. Id has to be ObjectId. But your value is string.

To solve it you need to use ;

mongoose.Types.ObjectId(req.params.id)
const updatedUser = await User.findByIdAndUpdate(mongoose.Types.ObjectId(req.params.id), req.body, {new:true, runValidators:true})

Try this, If "\n" makes problem, you need to send data as string like ObjectId ( '632aa0c8930ca0decc7d042b' ) .

If it always comes with "\n" so you need to split it then write into findByIdAndUpdate as ;

const parameter =req.params.id.split('\')[0]
User.findByIdAndUpdate(mongoose.Types.ObjectId(parameter), req.body, {new:true, runValidators:true})

I hope, it is helpful for you. If it doesn't, please comment.

Related