首页 > 解决方案 > 在猫鼬中使用“删除”后中间件的问题

问题描述

我对猫鼬有一个严重的问题,我有一个博客应用程序,用户可以在其中写帖子和评论,这是我的模式:

用户架构:

var userSchema = new mongoose.Schema({
firstName:{
    type:String,
    required:true
},
lastName:{
    type:String,
    required:true
},
email:{
    type:String,
    required:true,
    unique:true
},
picture:{
    type:String
},
about:{
    type:String
},
role:{
    type: String,
    default: 'user',
    enum : ['user', 'admin']
},
password:{
    type:String,
    required:true,
    select: false
},
passwordConfirm:{
    type:String,
    required:true,
},
active:{
    type: Boolean,
    default: false
},
passwordChangedAt: Date,
passwordToken: String,
passwordTokenExpire: Date,
activeToken: String,
activeTokenExpire: Date,
newEmailToken: String,
newEmailTokenExpire: Date,
newEmail: String });

发布架构:

var postSchema = new mongoose.Schema({
title:{
    type:String,
    required:true,
    unique:true,
},
content:{
    type:String,
    required:true
},
likeCount:{
    type: [String]
},
user:{
    type: mongoose.Schema.ObjectId,
    ref:'User',
    required:true
},
category:{
    type:mongoose.Schema.ObjectId,
    ref: 'Category',
    required:true
}},{ timestamps: true });

评论架构:

var commentSchema = new mongoose.Schema({
content:{
    type:String,
    required:true
},
user:{
    type:mongoose.Schema.ObjectId,
    ref: 'User',
    required:true
},
post:{
    type:mongoose.Schema.ObjectId,
    ref: 'Post',
    required:true
}},{ timestamps: true });

当用户删除帖子时,属于该帖子的评论也必须删除,这就是我实现此功能的方式:

postSchema.post('remove', async function(doc,next){
await Comment.deleteMany({post: doc.id});
next();})

它工作得很好,现在当用户删除他的帐户时,他的评论和他的帖子也必须被删除,所以我首先在用户模型中尝试使用此代码:

userSchema.post('remove', async function(doc,next){
await Comment.deleteMany({user: doc.id});
await Post.remove({user: doc.id});
next();});

帖子和用户的评论已成功删除,但评论属于那些帖子仍然存在!所以当我从 userSchema.post('remove',...) 中间件中删除帖子时 postSchema.post('remove',...) 中间件不会运行我不知道问题出在哪里,但我再次尝试使用此代码:

userSchema.post('remove', async function(doc,next){
await Comment.deleteMany({user: doc.id});
const posts = await Post.find({user: doc.id});
posts.map(async post => await Comment.deleteMany({post: post.id}));
await Post.deleteMany({user: doc.id});
next();});

它工作得很好,所以当用户删除他自己的帐户时,上面的中间件会删除他的评论和帖子,并且评论属于帖子。

也许这个应用程序没问题,但想象一下我有一个包含许多模型和复杂架构的大型应用程序,在不影响性能的情况下实现此功能的最佳方法是什么

标签: mongodbmongoosemongodb-querymiddlewaremongoose-schema

解决方案


推荐阅读