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

Bru*_*dus 5 arrays mongoose mongodb

在我的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);
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用以下方法找到一个:

Answer.findById(doc.answer, function(err, doc){});
Run Code Online (Sandbox Code Playgroud)

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

如果重复,可以随时关闭此问题,但是在谷歌搜索,堆栈溢出以及相关主题中找不到我的答案。

谢谢你的帮助!

Amo*_*rni 7

为什么不简单地在架构上添加自己的'remove'Mongoose中间件Question来删除所有其他文档,即引用问题的答案。

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

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


如果您有兴趣使用级联删除,您可以查看为其构建的 npm 模块。级联关系 - 链接NPMGit

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