2011-08-07 54 views
0

好的,我在更新模型時遇到了問題。我可以創建一個文檔,它工作得很好,但是當我嘗試更新時,出現錯誤。模型已創建,但無法使用Express,Mongoose和NodeJS更新

/Users/User/Sites/project/app.js:182 
     a.features.kids = req.body.a.features.kids; 
             ^
TypeError: Cannot read property 'kids' of undefined 

這個模型看起來是這樣的:

Affiliate = new Schema({ 
    'name': String, 
    'address': String, 
    'features': { 
     'kids': { type: Boolean, default: false }, 
    } 
}); 

我的表單域看起來是這樣的。它們用於創建和更新時添加了用於更新的額外字段:

<input type="text" name="a[name]" id="a[name]" /> 
<input type="text" name="a[address]" id="a[address]" /> 
<input <% if (a.features.kids) { %>checked <% }; %>type="checkbox" name="a[features.kids]" id="a[features.kids]" /> 

用於創建新項目的代碼。這工作正常,所有的信息都正確添加:

var a = new Affiliate(req.body.a); 

a.save(function() { 
    res.redirect('/admin'); 
}); 

斷碼更新項目:

Affiliate.findOne({ _id: req.params.id}, function(err, a) { 
    if (!a) return next(new NotFound('Affiliate not found')); 
    a.name = req.body.a.name; 
    a.address = req.body.a.address; 
    a.features.open_gym = req.body.a.features.kids; 

    a.save(function(err) { 
     res.redirect('/admin'); 
    }); 

}); 
+0

如果你是console.log req.body.a,你會得到什麼? 'a.name'和'a.address'是變量的名字嗎? –

+0

記錄req.body.a給我 '{A: {ID: '4e1f803999decab541000003', 名:「名稱這裏, 地址: '1234街', 'features.kids': '上'}} ' 如何爲孩子命名我的表單字段有問題嗎? – Smosh

+0

我建議不要在你的字段ID中使用點。例如,如果你使用features_kids,它就可以正常工作,正如Peter Lyons在下面提到的那樣。你最終做了很多好處不多的解決方法。 –

回答

0

嗯,我想明確bodyParser很可能無法解釋a[features.kids]你期望的方式。您可以通過req.body.a['features.kids']訪問該字段,因爲它沒有解釋嵌入時段。嘗試命名您的<input>a[features][kids]並查看是否解析出您期望的對象結構。

+0

謝謝彼得!它完美的作品。 – Smosh

相關問題