【发布时间】: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 或只从数组中删除它们。但我希望删除对象,而不仅仅是该数组中的引用。
如果重复,请随时关闭此问题,但我在谷歌搜索、堆栈溢出和相关主题中没有找到答案。
感谢您的帮助!
【问题讨论】:
-
mongodb/mongoose findMany - find all documents with IDs listed in array 的可能重复项。这我确实是重复的。以上内容应该可以帮助您到达需要去的地方。
-
@Brudus:关于中间件使用的任何更新。它对你有用吗?