更新Mongodb与node 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")

谢谢

好了,这里有几件事我想我可以帮你澄清一下:

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路由参数

您可能还需要查看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   
  });

最新更新