[英]How can I update a document in Mongoose?
我试图允许用户使用带有方法覆盖包的表单更新现有的mongoose文档。 我已经阅读了有关该问题的其他Stackoverflow帖子,但它们似乎都没有解决我的问题。 我希望用户能够看到他们创建的现有文档,使用新值提交表单,并让它更新数据库。
我试过这里提供的解决方案如何在Mongoose中更新/ upsert文档? 除其他外,它没有奏效。
我已设置此初始路线以显示单个文档:
// EDIT - edit location route
router.get("/location/:id/edit", function(req, res) {
Location.findById(req.params.id, function(err, foundLocation){
res.render("./locations/edit", {location: foundLocation});
});
});
这导致他们使用此表单登录页面以更新该文档的信息
<form action="/location/<%= location._id %>?_method=PUT" method="POST">
<div class="form-group"><input class="form-control" type="text" name="location[name]" ></div>
<div class="form-group"><input class="form-control" type="text" name="location[image]" value="<%= location.image %>"></div>
<div class="form-group"><input class="form-control" type="text" name="location[longDescription]" value="<%= location.longDescription %>"></div>
<div class="form-group"><button class="btn btn-lg btn-primary btn-block">Submit!</button></div>
</form>
处理该PUT逻辑的路由是:
router.put("/location/:id", function(req, res) {
Location.findByIdAndUpdate(req.params.id, req.body.location, {new: true}, function(err, updatedLocation){
console.log(req.body.location);
if(err) {
console.log(err);
res.redirect("/search");
} else {
console.log(updatedLocation);
res.redirect("/location/" + req.params.id);
}
});
});
我遇到的问题是这条路线没有触发任何错误,但它也没有更新文档。 我试过console.log req.body.location,它返回undefined。 我觉得这可能是问题,但我不确定如何解决它
@Deda这是登录console.log(req.body)的内容
'location[image]':
'https://wekivaisland.com/wp-content/uploads/bartlettimage-4977.jpg',
'location[longDescription]': 'Edited Long Description' }
{ address:
{ street: '51 SW 11th Street Apt. 1537',
city: 'Miami',
state: 'FL',
zip: '12345',
country: 'United States' },
author: { id: 5d081e0afd38374b43ca0c14, username: 'danny' },
rating: 0,
_id: 5d08dd702456a30948947c73,
name: 'Random Place',
image:
'https://2.bp.blogspot.com/-yKPXCFHoNhQ/WPOOwjqA3QI/AAAAAAAABmQ/88DcGs-Cp5oXAv6fA6hn3J7NRUlYBaxgwCLcB/s1600/Screen%2BShot%2B2017-04-16%2Bat%2B11.33.00%2BAM.png',
longDescription: 'Place #2',
shortDescription: 'Place #2',
__v: 0 }```
This has been resolved. I just needed to set bodyParser extended to true.
It has previously read
```app.use(bodyParser.urlencoded({ extended: false }));``
by changing this to the code below everything worked properly.
```app.use(bodyParser.urlencoded({ extended: true }));```
我们可以看到您尝试启动API的请求吗? 你用什么工具来调试? 如果req.body.location
未定义,那肯定是个问题:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.