Home > Back-end >  How can I find a Post of a User?
How can I find a Post of a User?

Time:12-15

Hello I want to find posts which user has made ..

I do my request with JWT Token:

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

This is my create function :

exports.create = async (req, res) => {
 
  const { forumName, forumDescription } = req.body;
  const token = req.token;
  const forumExist = await Forum.findOne({ forumName: req.body.forumName });
  if(forumExist){
    res.status(400).send("Forum Exists already.");
  }  
  try{
  const owner = await User.findOne({userID:token._id});
  if (!forumName || !forumDescription) {
    res.status(400);
    throw new Error("Please Fill all the feilds");
    return;
  }
  else {
    const newForum = new Forum({ forumName, forumDescription,user: owner.userID });
    newForum.user = owner;
    const createdNote = await newForum.save();
    res.status(201).json(createdNote);
  }
  }catch(err){
    res.status(400).send(err);
  }
};

This is my function where I want to get the Posts which the user has made :

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

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

  res.json(forum);
}

And this is model which I have for Post:

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")
    },
});

Everytime I do a request it has this error :

UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ user: 'admin' }" (type Object) at path "_id" for model "Forum"

my generate Token :

const generateToken = (_id, userID) => {
  console.log('Signing token for ID ', _id,userID);
  console.log('Secret key is ', process.env.JWT_KEY);
  const token = jwt.sign({ _id,userID}, process.env.JWT_KEY, {
    expiresIn: "30d",
  });
  console.log('Signed token: ', token);
  return token;
  
};

CodePudding user response:

As you are using findById, you should only send the id as argument function.

If you want to search with filter query, use find method

CodePudding user response:

const extractToken = (rawTokenHeader) => {
  
  if(!rawTokenHeader) { return undefined; }

  // Remove bearer and extract token value
  const temp = rawTokenHeader.split(' ');
  if(!temp || temp.length != 2) { return undefined; }

  // Return encoded token
  return temp[1];

};

module.exports = function(req,res,next){
  // Get authorization header
  const rawTokenHeader = req.header('Authorization');

  // Get token value
  const token = extractToken(rawTokenHeader);

  // No token -> No access
  if(!token) {
    console.log('No token in request');
    // Access denied
    return res.status(401).send('Access Denied');
  }
  
  // Verify token
  try {
    const decoded = jwt.verify(token, process.env.JWT_KEY);

    req.token= decoded;
    
    //console.log(token.userID);
        // Proceed
    next();
  } catch(err) {
    console.error('Error in JWT check: ', err);
    // Tell client something went wrong
    res.status(400).send('Invalid Token');
  }
}

this is my middleware ..

  • Related