node.js - 使用 Mongoose 访问数组数组中的对象

标签 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 显示)。有什么指示我应该做什么吗?

最佳答案

您可以使用$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/

相关文章:

node.js - 外部模块中的模式在 Node.js 中不起作用

node.js - 从 Azure AD 获取刷新 token 时出错

node.js - 使用 Express 和 node-archiver 即时生成 zip 存档

javascript - Node.JS——需要帮助理解原生流

javascript - 使用 MongoDB 和 Nodejs 传递两个查询

javascript - 在 Mongoose 查询中使用变量作为属性名称未返回正确结果

node.js - AngularJS 更新 mongoDB

node.js - 仅获取数组 mongoose 的最后一个元素

javascript - 如何在 Mongoose 中推送元素父级?

node.js - Mongoose .js : is it possible to change name of ObjectId?