简体   繁体   English

Mongoose - 转换为 ObjectId 失败

[英]Mongoose - Cast to ObjectId failed

I am working on a small blog app and I am stuck here at this error-我正在开发一个小型博客应用程序,但由于这个错误而被困在这里 -

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

I am using findById - Here is the code我正在使用 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
            });
        }
    });
});

Here is the app.js file这是 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");
});

here is new.ejs:这是 new.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 %>

and here is show.ejs这是 show.ejs

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

<% include ./partials/footer %>

After console.log, i got the right id but it has a space in the beginning like this在 console.log 之后,我得到了正确的 ID,但它在开头有一个空格,就像这样

  • ' 597c4ce202ca9c353fc80e8a' and in the url %20 adds up everytime before the id, like this -> http://localhost:5000/blogs/%20597c4ce202ca9c353fc80e8a and if i remove %20 from url then the requested page shows up. '597c4ce202ca9c353fc80e8a' 并且在 url %20 中每次都会在 id 之前加起来,就像这样 -> http://localhost:5000/blogs/%20597c4ce202ca9c353fc80e8a如果我从 url 中删除 %20 那么请求的页面就会出现。 I am stuck here for a long time and i have not find solution.我被困在这里很长时间了,我还没有找到解决办法。 please help请帮忙

It feels like ObjectId is not valid.感觉 ObjectId 无效。 That you are passing.你正在过去。 please check it with:请检查:

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

You need to specify into your model that your "id" is of type ObjectId, like below example:您需要在模型中指定您的“id”是 ObjectId 类型,如下例所示:

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

This should solve the issue!这应该可以解决问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 转换为 ObjectID 失败 - mongoose - Cast to ObjectID failed - mongoose castError ZCCADCDEDB567ABAE643E15DCF0974E503Z,转换为 ObjectId 失败 - castError Mongoose, cast to ObjectId failed Mongoose:转换为ObjectId失败的值 - Mongoose: Cast to ObjectId failed for value Mongoose 转换为 ObjectID 的值失败了......但为什么 - Mongoose cast to ObjectID failed for value... but why Mongoose DBrefs - 转换为ObjectId失败的值 - Mongoose DBrefs - Cast to ObjectId failed for value ZCCADCDEDB567ABAE643E15DCF0974E503Z - 转换为 ObjectId 失败,多个 ID - Mongoose - Cast to ObjectId failed, Multiple IDs Mongoose + MongoDB-尝试使用POSTMAN保存后,强制转换为ObjectID的值失败 - Mongoose + MongoDB - Cast to ObjectID failed for value after try save with POSTMAN 与猫鼬聚合时,在路径“ _id”的值“ xxx”的强制转换为ObjectId失败 - Cast to ObjectId failed for value “xxx” at path “_id” when aggregating with mongoose ZCCADCDEDB567ABAE643E15DCF0974E503Z:CastError:对于 model “”的路径“_id”处的值“未定义”,转换为 ObjectId 失败 - Mongoose: CastError: Cast to ObjectId failed for value “undefined” at path “_id” for model “” Mongoose:CastError:对于模型“”的路径“_id”中的值“”,CastError:Cast to ObjectId失败 - Mongoose: CastError: Cast to ObjectId failed for value "" at path "_id" for model ""
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM