我想使用PUT方法更新mongodb数据库。我安装了method-override并包含在内,但仍然出现错误:
传入的参数必须是12个字节的单个字符串或24个十六进制字符的字符串。
代码如下:
//UPDATE ROUTE
app.put("/blogs/:id", function(req, res){
//let id = req.params.id;
//let newData = req.body.blog;
Blog.findByIdAndUpdate(req.params.id, req.body.blog, function(err, updatedBlog){
if (err){
console.log(err);
//res.redirect("/blogs");
} else {
res.redirect("/blogs/" + id);
}
});
});
ejs文件
<%- include('partials/header'); -%>
<div class="ui main text container segment" style="margin-top: 7.0em;">
<div class="ui huge header">Edit <%= blog.title %> </div>
<!--HTML does not support PUT request, we have to use
Method-Override by adding ?_method=PUT-->
<form class="ui form" action="/blogs/ <%= blog._id %>?_method=PUT" method="POST">
<div class="field">
<label for=""><Title></Title></label>
<!--Using value attribute instead of placehold to retrieve the data from the database-->
<input type="text" name="blog[title]" value="<%= blog.title %>">
</div>
<div class="field">
<label for="">Blog Image</label>
<input type="text" name="blog[image]" value="<%= blog.image %>">
</div>
<div class="field">
<label for="">Blog Content</label>
<textarea name="blog[body]" id="" cols="30" rows="10"> <%= blog.body %></textarea>
</div>
<input class="ui violet basic button" type="submit">
</form>
</div>
<%- include('partials/footer'); -%>
答案 0 :(得分:0)
you have to set code as below because we are using findByIdAndUpdate so we have to set some value for the update
app.put("/blogs/:id", function(req, res){
Blog.findByIdAndUpdate(req.params.id, {
$set: {
title: req.body.blog.title,
image: req.body.blog.image,
body: req.body.blog.body
}
}, function(err, updatedBlog){
if (err){
console.log(err);
//res.redirect("/blogs");
} else {
res.redirect("/blogs/" + id);
}
});
});