Batch Update an array in mongoose object

259 views Asked by At

My Schema is as below. A student can participate in any no. of events.and each Event can have any number of students.

Student{
name:String,
age:Number,
.
.
.,
events:{
 type:
  [
   {type:Schema.ObjectId,
    ref:'Event'}
  ]
}
}

Event{
title:String,
desc:String,
eventDate:Date,
participants:{
type:
      [{
      student: {type:Schema.ObjectId,
               ref:'Student'},
      status : String
      }]
}

}

My requirement: Every time,I create an event, I need to push all the participants of that event inside event object. and in turn, tag the event reference inside all the participants.

My code is

function handleTeamParticipants(eventObj, participants) {
    Student
        .find({
            $or: [{
                _id: participants[0].student._id
            }, {
                _id: participants[1].student._id
            }]
        })
        .populate('events events.participants events.participants.student')
        .exec(function(err, students) {

        var studentLength = students.length,
            result = [];
        var saveAll = function() {
            var doc = students.pop();
            Student.populate(doc, {
                path: 'events.participants.student',
                model: 'Student'
            }, function(err, student) {
                student.events.push(eventObj);
                student.save(function(err, saved) {
                    if (err) next(err); //handle error
                    result.push(saved);
                    if (--studentLength) saveAll();
                    else // all saved here
                    {

                        return res.status(200).send(eventObj);
                    }
                });
            });
        };
        saveAll();
    });

}

This code is working. So, this way, I get only the first two participants updated and in turn added to eventobj. But I want the find query to select all the participants.student._id

Please let me know the easy way to do it.

Thanks.

1

There are 1 answers

0
sabari On BEST ANSWER

I used lodash method pluck.

lodash.pluck(< arrayObj >,< attribute >);

will give the list of attribute values in the arrayObj.

studentList = lodash.pluck(pariticipants,"student"); studentIdList = lodash.pluck(studentList,"_id");