2016-11-06 38 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 
    });