使用mongoose访问数组数组中的对象

时间:2017-01-27 19:56:13

标签: node.js mongodb mongoose

我有以下结构,我试图删除参与者中的对象(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])
            })
    })
}

这是我到目前为止所做的,但显然它返回了联盟对象,我无法找到参与者,因为我不知道参与者在哪个部门(在样本中由XXXXX显示)。关于我应该做什么的任何指示?

1 个答案:

答案 0 :(得分:1)

您可以使用$pull根据条件删除数组元素:

League.update({
    'divisions.participants._id': participantId
}, {
    $pull: {
        'divisions.$.participants': {
            "_id": participantId
        }
    }
}, { multi: true }, function(err, res) {
    console.log(res);
});