2

I have the following structure and am trying to remove an object in participants (league.division.participants).

var participantSchema = new mongoose.Schema({
player: { type: mongoose.Schema.Types.ObjectId, ref: 'Player' },
record: { type: mongoose.Schema.Types.ObjectId, ref: 'ParticipantRecord' },
events: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Event' } ]
});

var divisionSchema = new mongoose.Schema({
    name: String,
    participants: [ participantSchema ]
});

var leagueSchema = new mongoose.Schema({
    name: String,
    startDate: { type: Date, default: Date.now },
    endDate: Date,
    locked: Boolean,
    leagueType: { type: mongoose.Schema.Types.ObjectId, ref: 'LeagueType' },
    game: { type: mongoose.Schema.Types.ObjectId, ref: 'Game' },
    divisions: [ divisionSchema ],
});

mongoose.model('League', leagueSchema);



var _RemoveDivisionParticipant = function(participantId)
{
    return new Promise((resolve,reject) =>{
        Models.League.findOne({'divisions.participants._id':participantId})
            .populate('divisions')
            .populate('divisions.participants')
            .exec((err, league) => {
                if (err) {return reject(err)}   
                league.divisions(XXXXX).participants(participantId).remove();
                console.log(league.divisions[0].participants[0])
            })
    })
}

This is what i have so far, but obviously it returns the league object, and i have no way of getting to the participants since I don't know which division the participant is in (Shown by XXXXX in the sample). Any pointers as to what I should do?

MarkB
  • 1,783
  • 2
  • 17
  • 32
  • http://stackoverflow.com/questions/30714938/lodash-property-search-in-array-and-in-nested-child-arrays may be this can help – Asif Saeed Jan 27 '17 at 20:12
  • Read the answers in this related post - http://stackoverflow.com/questions/14763721/mongoose-delete-array-element-in-document-and-save – SylonZero Jan 28 '17 at 00:05

1 Answers1

1

You can use $pull to remove an array element based on a condition :

League.update({
    'divisions.participants._id': participantId
}, {
    $pull: {
        'divisions.$.participants': {
            "_id": participantId
        }
    }
}, { multi: true }, function(err, res) {
    console.log(res);
});
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
  • Perfect. Thanks. Follow up question. As I typed up your solution, I accidentally used 'division' instead of 'divisions' in the pull, yet mongoose did not return an error. Any idea why? – MarkB Jan 28 '17 at 07:57
  • There is no error dispatched if nothing match your query (why would it be ?) but in the result, the number of modified result `res.nModified` will be 0 – Bertrand Martel Jan 28 '17 at 11:13
  • Still have a relational DB mindset, so i expected an error when he didn't find it. Thanks again – MarkB Jan 28 '17 at 11:40