Home > Back-end >  How can I find a forum by JWT Token?
How can I find a forum by JWT Token?

Time:12-15

I want to find forum by JWT Token .. so if a user made 3 forum I want to list them.

My Request shows this way :

###
http://localhost:8080/forum/getByOwnerID
Authorization: Bearer {{adminToken}}

Or this way :

###
http://localhost:8080/forum/getByOwnerID
Authorization: Bearer {{userToken}}

On both I want to find the forum which they have made..

I create a function like that :

exports.getByToken = async (req, res, next) => {
  const forum = await Forum.findById(req.token._id);

  if (forum) {
    res.json(forum);
  } else {
    res.status(404).json({ message: "Forum not found" });
  }

  res.json(forum);
}

But the result is Forum not found :/

My ForumModel.js :

const forumSchema = ({
    forumName: {
        type: String,
        required: true,
    },
    forumDescription: {
        type: String,
        required: true,
    },
    user: { 
        type: Schema.Types.ObjectId,
        
        ref: "User"
    },
    published_on: {
        type: String,
        default: moment().format("LLL")
    },
});

CodePudding user response:

if you passed those things in the token, Here is how you should do it.

const { forum:{ _id }} = req.user

All in to find the current user you should do something like this

const currentUser = req.user;

Am assuming the endpoint your working on is protected with jwt authentication.

CodePudding user response:

exports.getByToken = async (req, res, next) => {
  const forum = {forum:{_id}} = req.user

  if (forum) {
    res.json(forum);
  } else {
    res.status(404).json({ message: "Forum not found" });
  }

  res.json(forum);
}

I wrote this that way but forum is undefined is the error message

  • Related