【问题标题】:CastError: Cast to ObjectId failed for value " 60f0d02f36ee6f2e505369e8" (type string) at path "_id" for model "collection"CastError:模型“collection”的路径“_id”处的值“60f0d02f36ee6f2e505369e8”(类型字符串)转换为 ObjectId 失败
【发布时间】:2021-07-16 14:57:38
【问题描述】:
app.get("/posts/:postId", function (req, res) {
let requestedPostId = req.params.postId;

Post.findById(requestedPostId, function (err, post) {
    if (!err) {
       res.render("post", { postTitle:post.title, postBody:post.content });
    } else {
        console.log(err);
    }
 });
});

这是我得到的错误:

当我尝试将数据库中文档的现有 _id 放入 '''requestedPostId variable''' 时,代码运行正常,页面加载完美。

我的意思是说,由于objectId的一些转换错误,数据库无法获取数据。

有人可以帮忙吗? 提前致谢。

【问题讨论】:

  • 你的id开头有个空格
  • 你能指定在哪里吗?
  • " 60f0... 如你所见
  • 为什么要在此处添加空间?在数据库中,objectId 中没有空格。那么如何摆脱这个不需要的空间呢?
  • 谢谢。我的错!我在 .ejs 文件中的 href 的 URL 中添加了一个空格。

标签: node.js mongoose


【解决方案1】:
There's a Space in the ID being added, You can remove it, or add the trim function before doing the update.

app.get("/posts/:postId", function (req, res) {
let requestedPostId = (req.params.postId).trim();

Post.findById(requestedPostId, function (err, post) {
    if (!err) {
       res.render("post", { postTitle:post.title, postBody:post.content });
    } else {
        console.log(err);
    }
 });
});

【讨论】:

    猜你喜欢
    • 2021-09-06
    • 2021-12-04
    • 1970-01-01
    • 2022-09-29
    • 2020-11-19
    • 2021-07-04
    • 2017-08-18
    • 2020-12-10
    • 2021-02-21
    相关资源
    最近更新 更多