Mongoose:删除引用对象时删除数组中所有引用的对象

时间:2016-06-26 14:57:46

标签: arrays mongodb mongoose

在我的MEAN应用程序(Angular2)中,我希望在删除对象本身时删除所有引用的对象。我使用Mongoose删除中间件。所以我的question.js文件看起来像这样:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Answer = require('../models/answer');

var QuestionSchema = new Schema({
    content: {type: String, required: true},
    questionTxt: {type: String, required: true},
    position: {type: Number, min: 0, required: true},
    answers: [{type: Schema.Types.ObjectId, ref: "Answer"}],
    followUpQuestions: [{type: Schema.Types.ObjectId, ref: "Question"}],
    additionalInfoText: {type: String},
    lastChangedBy: {type: Schema.Types.ObjectId, ref: 'User'},
    lastChanged: {type: Date},
    isRoot: {type: Boolean}
});

/**********************************************
 *  Deletes all answers and questions referenced by this question
 ***********************************************/

schema.post('remove', function(doc) {
    var deletedQuestion = doc;
        //code missing to find the answers and delete all referenced answers
    });
});

module.exports = mongoose.model('Question', QuestionSchema);

我知道我可以通过以下方式找到:

Answer.findById(doc.answer, function(err, doc){});

我现在也可以使用find方法查找多个元素并添加查询。但我只是找到了一些东西来找到一个特定的id或只从数组中删除它们。但我希望删除对象,而不仅仅是该数组中的引用。

如果它是重复的,请随时关闭此问题,但在谷歌搜索,堆栈溢出和相关主题后我没有找到答案。

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

为什么不在'remove'架构上添加自己的Question Mongoose middleware以删除所有其他文档,即引用该问题的答案。

示例:在中间件功能中,您可以执行以下操作:

QuestionSchema.pre('remove', function(callback) {
    // Remove all the docs that refers
    this.model('Answers').remove({ Question_Id: this._id }, callback);
});

<小时/> 如果您有兴趣使用级联删除,可以查看为其构建的npm模块。 层叠关系 - 链接NPM&amp; Git

  

$ cascadeDelete定义删除文档是否也会删除其相关文档。如果将其设置为true,则删除主文档时将删除所有相关文档。