findByIdAndRemove导致错误

时间:2018-01-27 21:11:52

标签: javascript node.js mongodb express mongoose

任何人都可以帮助在下面的删除路线中找出为什么mongoose findByIdAndRemove ...

//DELETE Route
app.delete("/blogs/:id", function(req, res){
  //Destroy blog
  Blog.findByIdAndRemove(req.params.id, function(err){
    if(err){
      res.send(err);
    } else {
      res.redirect("/blogs");
    }
  });
});

...生成以下错误:

message: "Cast to ObjectId failed for value "5a6a8f967c9a190507b03433 " at path "_id" for model "Blog"",
name: "CastError",
stringValue: ""5a6a8f967c9a190507b03433 "",
kind: "ObjectId",
value: "5a6a8f967c9a190507b03433 ",
path: "_id"

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

问题是您在方法findOneByIdAndRemove需要ObjectId时从客户端发送16个字符长的字符串。这样做可以消除这个问题,

var mongoose = require('mongoose'); //remove it as you might already it
var ObjectId = mongoose.Types.ObjectId;

app.delete("/blogs/:id", function(req, res){
  //Destroy blog
  Blog.findByIdAndRemove(ObjectId(req.params.id), function(err){
    if(err){
      res.send(err);
    } else {
      res.redirect("/blogs");
    }
  });
});

另外,请确保_id长度为16个字符,并且不允许任何一方留空。

答案 1 :(得分:0)

非常感谢@vicbyte和Nilesh Singh的贡献。

实际上,由于id结尾处的空格,代码失败了:“5a6a8f967c9a190507b03433”。该空间来自发出DELETE的表单:

<form id="delete" action="/blogs/<%= blog.id %> ?_method=DELETE" Method ="POST">
  <button class = "ui red basic button">Delete</button>
</form> 

修改下面的表格......

<form id="delete" action="/blogs/<%= blog.id %>?_method=DELETE" Method ="POST">
  <button class = "ui red basic button">Delete</button>
</form>

...清除了错误。