开发者

Model is created but can't update with Express, Mongoose, and NodeJS

Alright so I'm having a problem with updating a model. I can create a Document and it works just fine but when I try to update, I get an error.

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

The model looks like this:

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

My form fields looks like this. They are used for both creating and updating with extra fields added for updating:

<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]" />

Code for creating a new item. This works fine and all the information is added properly:

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

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

Broken code for updating an item:

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

});


Yeah, I think the express bodyParser is probably not interpreting a[features.kids] the way you expect. You can access the field with req.body.a['features.kids'] since it's not interpreting that embedded period. Try naming your <input> a[features][kids] and see if that parses into the object structure you are expecting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜