【问题标题】:CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for modelCastError:模型的路径“_id”处的值“未定义”(类型字符串)转换为 ObjectId 失败
【发布时间】:2021-12-04 14:49:05
【问题描述】:

我正在开发一个应用程序,但是当我尝试发布课程时,我得到的错误有点像有线但可能与 mongoose mondo db 数据库有关。

export const publishCourse = async (req, res) => {
  try {
    const { courseId } = req.params;
    // find post
    const course = await Course.findById(courseId)
      .select("instructor")
      .exec();
    // is owner?
    if (course.instructor._id != req.user._id) {
      return res.status(400).send("Unauthorized");
    }

    const updated = await Course.findByIdAndUpdate(courseId, {published: true}, {new: true}).exec();

    res.json(updated);
  } catch (err) {
    console.log(err);
    return res.status(400).send("Publish course failed");
  }
};

【问题讨论】:

  • 我将其读作“试图将未定义转换为数字”。这表明 courseId 未定义。 Console.log 并找出答案。您还可以查看堆栈跟踪以了解这是哪一行。

标签: reactjs mongodb mongoose


【解决方案1】:

也许您从请求参数const { courseId } = req.params 检索的参数不是有效的objectId,因此findById 会抛出您提到的错误,请在调用findById 之前尝试确保courseId 是有效的objectId,也许你可以在你的代码中使用它:

const { courseId } = req.params;
if(ObjectId.isValid(courseId)){
  // throw some error document not found for example.
}

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 2021-07-04
  • 2021-06-05
  • 2018-03-17
  • 2020-11-19
  • 2021-07-04
相关资源
最近更新 更多