删除嵌套对象引用mongoose

时间:2015-05-03 23:13:56

标签: mongodb mongoose

我的应用程序中有几个mongoose模型 - 赋值,submisssion和文件。

var assignmentSchema = new Schema({
    submissions:[{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Submission'
    }]
});
var submissionSchema = new Schema({
    assignment: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Assignment'
    },
    files: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'File'
    }],
})
var fileSchema = new Schema({
    submission: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Submission'
    }
})

我为分配定义了一个删除钩子,所以当从我的mongodb中删除一个赋值时,所有提交都会被删除。

assignmentSchema.pre('remove', function (next) {
    var assignment = this;

    assignment.model('Class').update(
        {_id: {$in: assignment.classes}},
        {$pull: {assignments: assignment._id}},
        {multi: true},
        next
    );

    //will delete all submissions that were in the assignment
    assignment.model('Submission').remove(
        {_id: {$in: assignment.submissions}}).exec();
        next
});

它运行正常,但我还想删除与已删除提交相关的所有文件。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

您必须为提交文件设置预删除挂钩 然后在您的assignmentSchema循环中通过assignment.submissions数组,找到每个分配文档并对该文档执行删除。 这是一个例子。未经测试。

assignmentSchema.pre('remove', function(nextAction) {
    var assignment = this;

    assignment.model('Class').update({
            _id: {
                $in: assignment.classes
            }
        }, {
            $pull: {
                assignments: assignment._id
            }
        }, {
            multi: true
        },
        next
    );

    Async.each(assignment.submissions, function(subId, next) {
        submissionSchema.findById(subId).exec(function(err, submission) {
            submission.remove();
            next();
        })
    }, function() {
        nextAction();
    })
});



submissionSchema.pre('remove', function (next) {
///remove files here.
})