Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update nested array with Express and Mongoose

I have an Express application with Mongoose. I have a model

var AttendeeSchema   = new Schema({
    name: String,
    registered: Boolean
});

var EventSchema   = new Schema({
    name: String,
    description: String,
    attendees : [AttendeeSchema],
    created: { type: Date, default: Date.now },
    updated: { type: Date, default: Date.now }
});

The code for creating an event is:

router.route('/:event_id')
    .get(function(req, res) {
        Event.findById(req.params.event_id, function(err, event) {
            if (err)
                res.send(err);
            res.json(event);
        });
    })

    .put(function(req, res) {
        Event.findById(req.params.event_id, function(err, event) {

            if (err)
                res.send(err);

            event.name = req.body.name;
            event.description = req.body.description; 
            event.attendees: req.body.attendees;

            event.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Event updated successfully!' });
            });

        });
    })

The code for updating an event is:

router.route('/:event_id')    
    .put(function(req, res) {
        Event.findById(req.params.event_id, function(err, event) {

            if (err)
                res.send(err);

            event.name = req.body.name;
            event.description = req.body.description; 
            event.attendees: req.body.attendees;

            event.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Event updated successfully!' });
            });

        });
    })

The problem is that events are being created successfully however when I try to update an event, it only updates the event name and description, but not changes to the attendees name or registered status. I also noticed that the version is not updated from "__v0" to "__v1"

Anyone some hints as to why I cannot update attendee specific information with the above code?

like image 969
wiwa1978 Avatar asked Sep 14 '26 12:09

wiwa1978


1 Answers

It looks like you need a = where you have a : ;)

event.attendees: req.body.attendees;
like image 119
Andrew Lavers Avatar answered Sep 16 '26 06:09

Andrew Lavers