【问题标题】:The method "findById" is not working, even though I am providing the correct Object Id“findById”方法不起作用,即使我提供了正确的对象 ID
【发布时间】:2020-07-16 03:49:40
【问题描述】:

我正在向我的本地主机发送 PUT 请求

http://localhost:3000/vidly.com/api/genres/5e87a056ee45fc0b300569c8

我的 PUT 路由处理程序代码是:-

router.put("/:id", async (req, res) => {
  const result = genreValidation(req.body);

  if (result.error) {
    return res.status(400).send(result.error.details[0].message);
  }

  console.log(req.params.id);
  const genre = await Genres.findById(req.param.id);
  console.log(genre);
  if (!genre)
    return res.status(404).send(`Bro, we dont have any genre of such Id..`);

 genre.set({
    genreName: req.body.genreName,
  });
  await genre.save();
  console.log(genre);
  return res.send(genre);
});

我使用了 findByIdAndUpdate() 和 findOne() 方法,但在所有情况下,我的 PUT 请求都不起作用,并且流派常量始终为 NULL!

【问题讨论】:

  • 试试const genre = await Genres.findById(mongoose.Types.ObjectId(req.param.id));

标签: javascript node.js mongodb mongoose postman


【解决方案1】:

我希望我可以对此发表评论,但我没有足够的声誉:

您确定使用req.param.id 是正确的,而不是req.params.id 在'param' 末尾使用's' 吗?您在上面的 console.log 中使用了复数,但在 findById 方法中没有使用

  //this is correct
  console.log(req.params.id);
  //I don't think this is without the 's'
  const genre = await Genres.findById(req.param.id);

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 2017-11-20
    • 2011-07-22
    • 2013-08-10
    • 1970-01-01
    • 2020-04-30
    • 2015-06-18
    • 1970-01-01
    • 2017-03-24
    相关资源
    最近更新 更多