【问题标题】:How can I find a Post of a User?如何找到用户的帖子?
【发布时间】:2023-03-30 19:38:01
【问题描述】:

您好,我想查找用户发布的帖子..

我使用 JWT Token 完成我的请求:

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

这是我的创建函数:

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

这是我想要获取用户发布的帖子的功能:

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

这是我为 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")
    },
});

每次我发出请求时都会出现此错误:

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

我的生成令牌:

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;
  
};

【问题讨论】:

  • 您应该使用 .findOne() 而不是 (.findById())[mongoosejs.com/docs/api.html#model_Model.findById],因为您的搜索条件不是 ID 本身:const forum = await Forum.findOne({ user: req.token._id })
  • @Xeelley 这不起作用:/
  • 如果你想得到用户,你为什么要搜索论坛用户关系?有什么理由不能直接使用用户模式进行搜索? “admin”也不是ObjectId,它是用户模式的主键吗?
  • 我不想因此获得用户。我想获取用户发布的帖子。我可以通过帖子的 id 获取所有帖子或获取帖子,但我无法通过给定的令牌获取帖子。
  • 这就是我要说的:"admin" 看起来不像令牌,而且我相信令牌不是用户模式主键,因为 .findOne 也不起作用。

标签: javascript node.js mongodb mongoose


【解决方案1】:

当您使用 findById 时,您应该只将 id 作为参数函数发送。

如果要使用过滤查询进行搜索,请使用find 方法

【讨论】:

  • 不会改变任何东西...
  • req.token._id === '管理员'。这是正确的身份证吗?您应该发送一个 objectId。类似于:await Forum.findById("61ae5a282b95e28f371cd0b9");
  • 但是我想通过token找..
  • 解码后的令牌有效负载必须具有用于查找文档的值。如果此值为 ObjectId,请使用 findById 并将其作为参数传递。如果它是另一个字段,请使用 findOne 在这里使用:await Forum.findOne({ forumName: req.body.forumName })
  • 另外,请确保在登录过程中创建 jwt 时包含此值。
猜你喜欢
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多