【问题标题】:Mongoose Referenced Schemas and MiddlewareMongoose 引用的模式和中间件
【发布时间】: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。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    如果您仍然对答案感兴趣;

    您正在使用 remove(<query>) 在您的 Category 中间件中删除 Post。来自猫鼬文档;

    注意:remove() 没有查询挂钩,仅适用于文档。如果你 设置一个 'remove' 钩子,当你调用 myDoc.remove() 时它会被触发, 不是当你调用 MyModel.remove() 时。

    您需要获取 Post,然后对该文档调用 delete 以使其工作。

    【讨论】:

      猜你喜欢
      • 2019-12-08
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 2015-06-17
      • 2016-05-29
      • 2013-08-02
      • 2018-05-11
      • 2019-08-19
      相关资源
      最近更新 更多