【问题标题】:Model is created but can't update with Express, Mongoose, and NodeJS模型已创建但无法使用 Express、Mongoose 和 NodeJS 进行更新
【发布时间】: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。你最终做了很多变通办法,但收效甚微。

标签: node.js express mongoose


【解决方案1】:

是的,我认为快递bodyParser 可能没有按照您期望的方式解释a[features.kids]。您可以使用req.body.a['features.kids'] 访问该字段,因为它不解释嵌入的句点。尝试命名您的 &lt;input&gt; a[features][kids] 并查看它是否解析为您期望的对象结构。

【讨论】:

    猜你喜欢
    • 2011-06-28
    • 2018-08-15
    • 1970-01-01
    • 2013-09-27
    • 2016-08-01
    • 1970-01-01
    • 2021-12-29
    • 2021-12-06
    • 1970-01-01
    相关资源
    最近更新 更多