Protect api routes by authenticating user jwt

Hi guys, I have been stuck on this issue for some days now, and I have tried everything to get it to work with no avail, and I am hoping to receive the help I need.

I am trying to protect certain API’s in my application by using jwt’s, and I keep running into the problem below whenever I test out the protected route in postman

Below is the code I have written


route

Can someone please point out to me what I am missing, pleeeease!

Hi @Tlotliso_Lehola.

It seems like mongoose ODM is throwing an exception because it can’t cast ‘talks’ of type String to ObjectId.

What is the route you are testing? Could you please share the request body?

Try making the request without passing _id in the request body, and see if you still get the same exception. Hope this help.

Thanks,
Mahi

Hi, I did that and the problem still persists
I am basically trying to authenticate a user token, return that user, and retrieve a list of ‘talks’ from the database

Here is the controller of the route am testing

the route am testing

route

Could you please share the Mongoose schema for that collection?

User schema:


Talk schema:

I don’t think there is an issue with the schemas, the problem I am having is with the authorize method when I have to return the user

mongoose adds _id of type ObjectId since there’s not one defined in the Schema. If you are not passing _id in request body from Postman then you shouldn’t be seeing that error. Could you please step through the service code to see where exactly the exception is being thrown?

hey…so the issue is not with the authorize method. The issue is with the route for some weird reason. I found out that when I use this “/” route in Postman, it collects the data just fine. When I write anything after the slash like “/talks” it throws the same error again. Why do you think that may be? I mean this is a standard get API call, I shouldn’t be having such difficulty getting data

This topic was automatically closed after 180 days. New replies are no longer allowed.