【发布时间】:2017-03-13 17:24:34
【问题描述】:
我对使用 mongoose 进行开发(使用平均堆栈)相当陌生,并且我在当前的应用程序中遇到了我的 mongo/mongoose 理解问题。我想做的是在我的模式之间创建一个论坛风格的关系。
因此,类别模式位于根部。在一个类别下是帖子。一个帖子可以有属于它的 cmets。因此,当我删除一个类别时,我想要发生的事情是帖子将被删除(那里没问题),但我还想清理与所有已删除的帖子相关联的 cmets。我遇到的问题是当我的类别 .pre() 删除帖子时,我的帖子中的 .pre() 似乎没有被解雇。
目前我的类别架构:
var mongoose = require('mongoose');
var CategorySchema = new mongoose.Schema({
categoryname: String,
categoryslug: String,
categorydescription: String,
views: {type: Number, default: 0},
created: {type: Date, default: Date.now()},
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
});
CategorySchema.methods.addview = function(cb) {
this.views += 1;
this.save(cb);
};
// Middleware Remove all the Posts in the category when deleted
CategorySchema.pre('remove', function(next) {
this.model('Post').remove( { category: this._id }, next );
});
mongoose.model('Category', CategorySchema);
删除一个类别实际上会删除该类别中的所有帖子。 然后是我的帖子架构:
var PostSchema = new mongoose.Schema({
title: String,
postcontent: String,
author: {type: String, default: 'Developer'},
upvotes: {type: Number, default: 0},
downvotes: {type: Number, default: 0},
created: {type: Date, default: Date.now()},
views: Number,
active: {type: Boolean, default: true},
comments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}],
category: {type: mongoose.Schema.Types.ObjectId, ref: 'Category'}
});
...
PostSchema.pre('remove', function(next) {
// Remove all the comments associated with the removed post
this.model('Comment').remove( { post: this._id }, next )
// Middleware Remove all the category references to the removed post
this.model('Category').update({ posts: this._id },
{ $pull: { posts: { $in: [this._id] }} } , next);
});
mongoose.model('Post', PostSchema);
删除帖子确实会按预期删除与其关联的 cmets。但是当我删除一个类别并且帖子被删除时,中间件永远不会触发删除每个帖子的 cmets。
【问题讨论】: