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?

2

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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
Still have a relational DB mindset, so i expected an error when he didn't find it. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.