我正在尝试在MongoDB中更新一个实例化的模型('Place‘--我知道它在其他路径上是有效的),并且已经花了一段时间来尝试这样做。我还试图重定向回查看“位置”的页面,以查看更新的属性。
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)
});
});
我尝试了一堆不同的方法,但似乎不能得到它。
另外,我声明这三个{name,capital,and continent}变量的方式不会阻止进一步的操作吗?谢谢。一般的调试帮助也很受欢迎。Console.log(名称)(就在声明的下面)不记录任何内容。
玉石形态:
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")
发布于 2011-02-17 14:39:23
在更新任何内容之前,您必须找到文档:
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提供的任何其他find方法。只需确保在更新文档之前获取了该文档。
发布于 2014-02-05 14:39:08
现在,我认为你可以这样做:
Place.findOneAndUpdate({name:req.params.name}, req.body, function (err, place) {
res.send(place);
});
你也可以通过id来查找:
Place.findOneAndUpdate({_id:req.params.id}, req.body, function (err, place) {
res.send(place);
});
发布于 2017-06-16 00:30:40
所以现在你可以直接通过id来查找和更新,这是针对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);
});
https://stackoverflow.com/questions/5024787
复制相似问题