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

7
在我的MEAN应用程序(Angular2)中,当删除对象本身时,我希望删除所有引用的对象。我使用Mongoose和remove中间件。因此,我的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或仅从数组中删除它们的内容。但我希望对象被移除,而不仅仅是在那个数组中的引用被删除。
如果有重复,请随意关闭此问题,但我在谷歌搜索、堆栈溢出和相关主题中都没有找到答案。
谢谢您的帮助!

可能是mongodb/mongoose findMany - find all documents with IDs listed in array的重复问题。这确实是一个重复的问题。上面的链接应该能帮助您找到所需的答案。 - Robert Moskal
@Brudus:中间件使用有任何更新吗?它对你有用吗? - Amol M Kulkarni
1个回答

8

为什么不在问题(Question)模式上添加您自己的'remove' Mongoose 中间件,以删除引用该问题的所有其他文档,即答案。

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

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

如果您想使用级联删除,可以查看专门为此构建的npm模块 Cascading-Relations - 链接NPM & Git。 $cascadeDelete 定义了是否删除文档时也会删除其相关文档。如果将其设置为 true,则在删除主文档时将删除所有相关文档。

谢谢你,我一直在尝试找出如何在数组中一次性删除一堆文档,但是从你的帖子中意识到:,创建一个实例方法,然后循环调用它!轻松搞定!谢谢! - twknab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接