javascript - 如何在 Mongoose 中更新文档?
问题描述
我试图允许用户使用带有方法覆盖包的表单来更新现有的猫鼬文档。我已阅读有关此问题的其他 Stackoverflow 帖子,但似乎没有一个可以解决我的问题。我希望用户能够看到他们创建的现有文档,提交带有新值的表单,并让它更新数据库。
我已经尝试过此处提供的解决方案如何在 Mongoose 中更新/更新文档?除其他外,它没有奏效。
我已经设置了这个初始路径来显示单个文档:
// 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 并且它返回未定义。我觉得这可能是问题,但我不知道如何解决它
@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
未定义,那肯定是个问题:)
推荐阅读
- php - API 调用错误 curl_setopt_array(): 不能将输出类型的流表示为 STDIO 文件*
- python - python tkinter canvas create_line 函数返回值?
- python - VSCode 鼠标悬停在 Python 关键字上不起作用
- python - 将 numpy 数组发送到 Bokeh 回调以作为音频播放
- jquery - JQuery - 将元素属性设置为他的兄弟文本
- bar-chart - 如何显示之前的 CME RTH 高点和低点
- data-science - 使用统计数据提取给定数据集中的缺失变量?
- python - 如何在 Python3 中并行运行语句
- gnuplot - Gnuplot 5.4 版补丁级别 1:绘制多个具有单个标题的数据集(图例条目)[在 5.4.2 版中解决]
- typo3 - Powermail 使用标记/变量作为 RTE 提交页面中的链接