2011-02-17 86 views
19

我想在MongoDB中更新一個實例化的模型('Place' - 我知道它可以從其他路徑中工作),並花了一段時間試圖正確地做到這一點。我還嘗試重新導向到查看「地點」以查看更新屬性的頁面。Mongoose,Express,NodeJS更新模型

節點V0.4.0,快速v1.0.7,貓鼬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) 
}); 

});

我試過了一堆不同的方法,但似乎無法得到它。
另外,是不是我如何聲明阻止進一步操作的三個{名稱,資本和大陸}變量?謝謝。一般調試幫助也表示讚賞。 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") 

回答

32

你必須找到任何更新前的文件:使用你有相同的設置

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,你可以使用貓鼬提供的任何其他查找方法。只需確保在更新文檔之前獲取文檔。

+0

這就是我如何做到的。 – Carlosedp 2011-02-22 18:05:16

0

我認爲你的問題是,你正在使用節點0.4.0 - 嘗試移動到0.2.6與它應該工作。 bodyDecoder沒有在節點> = 0.3.0中填充req.body.variable字段,在github上記錄了一個問題。

17

現在,我想你可以這樣做:

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); 
}); 
0

所以現在可以直接通過ID發現,這是貓鼬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); 
});