【问题标题】:Mongoose - Cast to ObjectId failedMongoose - 转换为 ObjectId 失败
【发布时间】:2018-01-06 00:15:06
【问题描述】:

我正在开发一个小型博客应用程序,但我遇到了这个错误 -

{
  "message": "Cast to ObjectId failed for value \" 597c4ce202ca9c353fc80e8a\" at path \"_id\" for model \"Blog\"",
  "name": "CastError",
  "stringValue": "\" 597c4ce202ca9c353fc80e8a\"",
  "kind": "ObjectId",
  "value": " 597c4ce202ca9c353fc80e8a",
  "path": "_id"
}

我正在使用 findById - 这是代码

app.get("/blogs/:id", function(req, res) {
    Blog.findById(req.params.id, function(err, foundBlog) {
        if (err) {
            res.send(err);
        } else {
            res.render("show", {
                blog: foundBlog
            });
        }
    });
});

这里是 app.js 文件

const bodyParser = require('body-parser'),
mongoose         = require('mongoose'),
express          = require('express'),
app              = express();

//APP CONFIG
mongoose.connect("mongodb://localhost/blog_rest");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true}));

//MONGOOS MODEL CONFIG
var blogSchema = new mongoose.Schema({
  title: String,
  image: String,
  body: String,
  created: { type: Date, default: Date.now}
})

var Blog = mongoose.model("Blog", blogSchema);

// Blog.create({
//   title: "TEST BLOG",
//   image: "https://images.pexels.com/photos/457443/pexels-photo-457443.jpeg?h=350&auto=compress&cs=tinysrgb",
//   body: "First App in the series"
// })

//RESTFUL ROUTES
app.get("/", function (req,res) {
  res.redirect("/blogs");
});

//INDEX ROUTE
app.get("/blogs", function (req,res) {
  Blog.find({}, function (err,blogs) {
    if(err){
      // res.send("ERROR");
      console.log(err);
    }
    else {
      res.render("index", {blogs: blogs});
    }
  })
});

//NEW ROUTE
app.get("/blogs/new", function (req,res) {
  res.render("new");
});

//CREATE ROUTE
app.post("/blogs", function (req,res) {
  //Create Blog///////Blog.create takes two parameters first is the data which is in req.body.blog and second is the callback function
  Blog.create(req.body.blog, function (err, newBlog) {
    if (err) {
      res.render("new");
    }
    else {
      res.redirect("/blogs");
    }
  });
});

//SHOW ROUTE
app.get("/blogs/:id", function (req,res) {
  //String.prototype.trim(req.params.id);
  console.log(req.params.id);
  Blog.findById(req.params.id, function (err,foundBlog) {
    if (err) {
      res.send(err);
    } else {
      res.render("show", {blog: foundBlog});
    }
  });
});




app.listen(5000, function () {
  console.log("Server is listening on Port: 5000");
});

这里是新的.ejs:

<% include ./partials/header %>

<div class="ui main text container segment">
    <div class="ui huge header">New Blog</div>
    <form class="ui form" action="/blogs" method="post">
        <div class="field">
            <label>Title</label>
            <input type="text" name="blog[title]" placeholder="Title">
        </div>
        <div class="field">
            <label>Image</label>
            <input type="text" name="blog[image]" placeholder="Image">
        </div>
        <div class="field">
            <label>Blog Content</label>
            <textarea name="blog[body]"></textarea>
        </div>
        <input class="ui blue inverted button" type="submit">
    </form>
</div>

<% include ./partials/footer %>

这里是 show.ejs

<div class="ui main text container segment">
    <div class="ui huge header"><%= blog.title %></div>
</div>

<% include ./partials/footer %>

在 console.log 之后,我得到了正确的 id,但它在开头有一个空格,就像这样

  • ' 597c4ce202ca9c353fc80e8a' 和 url %20 每次在 id 之前加起来,就像这样 -> http://localhost:5000/blogs/%20597c4ce202ca9c353fc80e8a 并且如果我从 url 中删除 %20 则显示请求的页面。 我被困在这里很长时间了,我还没有找到解决办法。请帮忙

【问题讨论】:

  • String.prototype.trim()。它删除了“空白”,这是您在 URL 中值的开头所拥有的。可能是因为您从中读取链接值的模板中存在错误。在其中一个地方修复它。
  • 使用 str.trim() 修剪您的 id 以删除空格
  • 我使用了 String.prototype.trim(req.params.id);但仍然是同样的错误
  • 您能发布发出请求的客户端代码吗?
  • @JamshidAsadzadeh,我已经添加了所有必要的文件

标签: javascript node.js mongodb express mongoose


【解决方案1】:

感觉 ObjectId 无效。你正在路过。 请检查:

var mongoose = require('mongoose');
mongoose.Types.ObjectId.isValid('your id here');

【讨论】:

  • 在此之后得到同样的错误,请理解我的问题并帮助我卡在这里。
  • 试试 findOne({_id: 'yourIdHere'});
【解决方案2】:

您需要在模型中指定您的“id”是 ObjectId 类型,如下例所示:

const Schema = new mongoose.Schema({
    _id: ObjectID,
    ....
})

这应该可以解决问题!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-14
    • 2013-03-24
    • 2021-09-05
    • 2020-07-23
    • 2021-03-09
    • 1970-01-01
    • 2020-04-18
    • 2020-12-16
    相关资源
    最近更新 更多