2016-11-06 33 views
0

我想添加一个编辑页面,我可以在mongodb中更改名称字段。但是我遇到了路由问题,任何人都可以请帮忙吗?这里是路由:用节点js express和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") 

谢谢

回答

0

好了,有几件事情我看到这里,我想我可以帮助清理:

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/en/guide/routing.html#route-parameters

您可能还需要考虑的findByIdAndUpdate方法的options说法,因为默认情况下它从查找返回原文件不更新后保存到数据库的一个已应用。

所以你的节点的代码应该是这样的:

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 
    });