【问题标题】:Mongoose: Delete all referenced objects in an array when deleting referencing objectMongoose:删除引用对象时删除数组中的所有引用对象
【发布时间】:2016-10-28 15:07:00
【问题描述】:

在我的 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 或只从数组中删除它们。但我希望删除对象,而不仅仅是该数组中的引用。

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

感谢您的帮助!

【问题讨论】:

标签: arrays mongodb mongoose


【解决方案1】:

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

示例:在中间件函数中,你可以这样做:

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


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

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

【讨论】:

  • 谢谢你,我试图弄清楚如何在一个数组中一次删除一堆文档,并从你的帖子中意识到:duh,做一个实例方法然后for循环并调用它!繁荣!成功!谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 2022-06-14
  • 2019-03-28
相关资源
最近更新 更多