Node Js猫鼬请求输入值未定义



我想添加一个编辑按钮到我的博客,首先我有一个post request/edit上的编辑按钮,然后它发送给你到另一个页面,在那里它自动填充与数据库内容。

最后,我有另一个编辑文件的post请求。我做了几次,它没有工作,所以我控制台记录它,我得到的值是未定义的。

app.post('/edit', (req,res)=>{
const editId = req.body.editBtn;
Blogdata.findOne({_id: editId}, (err, dataFound)=>{
// res.render('edit', {data: dataFound})
if(err){
console.log(err)
}else{
res.render('edit', {data:dataFound})
}
})
})

这会将您发送到ejs编辑文件

<%- include("partials/head") %> 
<form action="/editDone" method="POST" enctype="multipart/form-data">
<div class="form-group-login">
<label for="title">Title</label>
<input type="text" name="tit" id="title" value="<%= data.title %> ">
</div>
<div class="form-group-login">
<label for="desc">Description</label>
<input type="text" name="des"  id="desc" value="<%= data.description %> ">
</div>
<div class="form-group-login">
<input type="file" name="myFile" class="fileForm" value="<%= data.img %> ">
</div>
<button type="submit" class="btn-form-login" name="btnIdd" value="<%=data._id %>">Submit</button>

最后,当你点击这里的提交按钮时,它会发出另一个请求findoneandupdate的帖子,

app.post('/editDone', (req,res)=>{
const newTitle = req.body.tit;
const newDesc = req.body.des;
const newFile = req.body.myFile;
const edit2Id = req.body.btnIdd;
console.log(newTitle)
Blogdata.findOneAndUpdate({_id: edit2Id}, {title: newTitle, description: newDesc, img: newFile}, (err)=>{
if(err){
console.log("failed to update")
}else{
console.log("Updated Successfully")
}
})
})

谢谢!

您是否检查了实际的数据库以查看更改是否已提交?为了在响应中获得更新的数据,您应该像这样使用findOneAndUpdate:

result = await findOneAndUpdate(
{ _id: edit2Id },
{ title: newTitle, description: newDesc, ..etc },
{ new: true }
)

注意第三个字段,它导致mongo返回更新的文档而不是旧文档。你这样做的方式也很好,但请记住,即使你的更改已经提交到DB

,你也不会得到更新的文档作为回报。

最新更新