[英]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.