用Mongoose,Express,NodeJS更新模型

我试图更新一个实例化的模型('地方' – 我知道它从其他路线工作)在MongoDB中,花了一段时间,试图正确这样做。 我也试着重新回到查看“地点”来查看更新属性的页面。

Node v0.4.0,Express v1.0.7,Mongoose 1.10.0

架构:

var PlaceSchema = new Schema({ name :String , capital: String , continent: String }); 

控制器/路线:

 app.put('/places/:name', function(req, res) { var name = req.body.name; var capital = req.body.capital; var continent = req.body.continent; Place.update({ name: name, capital: capital, continent: continent}, function(name) { res.redirect('/places/'+name) }); 

});

我尝试了一堆不同的方式,但似乎无法得到它。
另外,是不是我如何宣布阻止进一步操作的三个(名称,资本和大陆)variables? 谢谢。 一般的debugging帮助也表示赞赏。 Console.log(name)(在声明下面)不logging任何东西。

玉形:

 h1 Editing #{place.name} form(action='/places/'+place.name, method='POST') input(type='hidden', name='_method', value='PUT') p label(for='place_name') Name: p input(type='text', id='place_name', name='place[name]', value=place.name) p label(for='place_capital') Capital: p input(type='text', id='place_capital', name='place[capital]', value=place.capital) p label(for='place_continent') Continent: p textarea(type='text', id='place_continent', name='place[continent]')=place.continent p input(type="submit") 

在更新任何内容之前,您必须先find文档:

 Place.findById(req.params.id, function(err, p) { if (!p) return next(new Error('Could not load Document')); else { // do your updates here p.modified = new Date(); p.save(function(err) { if (err) console.log('error') else console.log('success') }); } }); 

在生产代码中使用相同的设置为我工作。 而不是findById,你可以使用mongoose提供的任何其他查找方法。 只要确保在更新之前获取文档。

现在,我认为你可以做到这一点:

 Place.findOneAndUpdate({name:req.params.name}, req.body, function (err, place) { res.send(place); }); 

你也可以通过idfind:

 Place.findOneAndUpdate({_id:req.params.id}, req.body, function (err, place) { res.send(place); }); 

我认为你的问题是你正在使用节点0.4.0 – 尝试移动到0.2.6与它应该工作。 github上有一个问题,bodyDecoder没有在节点> = 0.3.0中填充req.body.variable字段。

所以现在可以通过id直接find,这是针对Mongoose v4的

Place.findByIdAndUpdate(req.params.id, req.body, function (err, place) { res.send(place); });

只要提到,如果你需要更新的对象,那么你需要传递{new: true}

Place.findByIdAndUpdate(req.params.id, req.body, {new: true}, function (err, place) { res.send(place); });