简体   繁体   English

使用Node JS Express和PUG(JADE)更新Mongodb

[英]Update Mongodb with node js express and PUG(JADE)

I am trying to add an edit page where I can change the name field in the mongodb.But I am having problems with the routing, can anyone please help? 我正在尝试添加一个编辑页面,在这里我可以更改mongodb中的名称字段。但是我在路由方面遇到问题,有人可以帮忙吗? here is the routing: 这是路由:

router.put('/edit', function(req, res) {
user.findByIdAndUpdate({_id: req.params.id},
                 {
        name: req.body.name
     });   
  });

And here is edit.pug 这是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")

Thank you 谢谢

Okay, there's a few things I see here I think I can help clear up: 好的,我在这里看到了一些东西,我想我可以帮忙清理一下:

user.findByIdAndUpdate - doesn't take an object for the first argument, just the _id. user.findByIdAndUpdate不使用对象作为第一个参数,仅使用_id。 http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

req.params - is connected to the route this callback is attached, so in your route you need to put a /:id to express that the value can change but will be available as req.params.id. req.params连接到此回调连接的路由,因此在您的路由中,您需要放置/:id来表示该值可以更改,但可以作为req.params.id使用。 Basically your route should look like router.put('/edit/:id', function(req, res) {... http://expressjs.com/en/guide/routing.html#route-parameters 基本上,您的路线应该看起来像router.put('/edit/:id', function(req, res) {... http://expressjs.com/zh-CN/guide/routing.html#route-parameters

You may also want look into the options argument of the findByIdAndUpdate method, because by default it returns the original document from its lookup not the one saved to the db after the updates have been applied. 您可能还希望查看findByIdAndUpdate方法的options参数,因为默认情况下,它从其查找中返回原始文档,而不是应用更新后保存到db中的原始文档。

so your node code should look like this: 因此您的节点代码应如下所示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM