【发布时间】:2011-10-21 15:29:29
【问题描述】:
好的,我在更新模型时遇到了问题。我可以创建一个文档,它工作得很好,但是当我尝试更新时,我得到了一个错误。
/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' 是变量的名称吗?
-
logging req.body.a 给我
{ a: { id: '4e1f803999decab541000003', name: 'Name Here', address: '1234 Street', 'features.kids': 'on'} }我为孩子命名表单字段的方式有问题吗? -
我建议不要在您的字段 ID 中使用点。例如,如果您执行 features_kids 它将正常工作,正如下面提到的 Peter Lyons。你最终做了很多变通办法,但收效甚微。