好的,我在更新模型時遇到了問題。我可以創建一個文檔,它工作得很好,但是當我嘗試更新時,出現錯誤。模型已創建,但無法使用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');
});
});
如果你是console.log req.body.a,你會得到什麼? 'a.name'和'a.address'是變量的名字嗎? –
記錄req.body.a給我 '{A: {ID: '4e1f803999decab541000003', 名:「名稱這裏, 地址: '1234街', 'features.kids': '上'}} ' 如何爲孩子命名我的表單字段有問題嗎? – Smosh
我建議不要在你的字段ID中使用點。例如,如果你使用features_kids,它就可以正常工作,正如Peter Lyons在下面提到的那樣。你最終做了很多好處不多的解決方法。 –