[英]Update Mongodb with node js express and PUG(JADE)
我正在尝试添加一个编辑页面,在这里我可以更改mongodb中的名称字段。但是我在路由方面遇到问题,有人可以帮忙吗? 这是路由:
router.put('/edit', function(req, res) {
user.findByIdAndUpdate({_id: req.params.id},
{
name: req.body.name
});
});
这是edit.pug
extends layout
block content
.main.container.clearfix
h1 Editing #{name}'s profile!
form(method="POST", action="/edit")
input(type="hidden", name="_method", value="PUT")
p Name:
input#name.form-control(type='text', value='#{name}')
p
input(type="submit")
谢谢
好的,我在这里看到了一些东西,我想我可以帮忙清理一下:
user.findByIdAndUpdate
不使用对象作为第一个参数,仅使用_id。 http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate
req.params
连接到此回调连接的路由,因此在您的路由中,您需要放置/:id
来表示该值可以更改,但可以作为req.params.id使用。 基本上,您的路线应该看起来像router.put('/edit/:id', function(req, res) {...
http://expressjs.com/zh-CN/guide/routing.html#route-parameters
您可能还希望查看findByIdAndUpdate
方法的options
参数,因为默认情况下,它从其查找中返回原始文档,而不是应用更新后保存到db中的原始文档。
因此您的节点代码应如下所示:
router.put('/edit/:id', function(req, res) {
user.findByIdAndUpdate(
req.params.id, // Which _id mongoose should search for
{ name: req.body.name }, //Updates to apply to the found document.
{ new: true }); // This tells mongoose to return the new updates back from the db
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.