我有以下结构,并尝试删除参与者 (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 显示)。有什么指示我应该做什么吗?
最佳答案
您可以使用$pull
根据条件删除数组元素:
League.update({
'divisions.participants._id': participantId
}, {
$pull: {
'divisions.$.participants': {
"_id": participantId
}
}
}, { multi: true }, function(err, res) {
console.log(res);
});
关于node.js - 使用 Mongoose 访问数组数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41902028/