mongodb - 在猫鼬中使用“删除”后中间件的问题
问题描述
我对猫鼬有一个严重的问题,我有一个博客应用程序,用户可以在其中写帖子和评论,这是我的模式:
用户架构:
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();});
它工作得很好,所以当用户删除他自己的帐户时,上面的中间件会删除他的评论和帖子,并且评论属于帖子。
也许这个应用程序没问题,但想象一下我有一个包含许多模型和复杂架构的大型应用程序,在不影响性能的情况下实现此功能的最佳方法是什么
解决方案
推荐阅读
- git - 我在哪里可以找到某些 github 命令的所有可能输出?
- javascript - 解决一个不存储输入的PHP?
- vue.js - 如何将 Foundation 断点实用程序导入 Vue-CLI 项目?
- angular - 有没有办法在不使用影子 DOM 的情况下以 8 角(或 9 角)制作自定义元素?
- javascript - 为什么 HTML5 Canvas 模糊?
- javascript - 从jQuery中的输入文本值中删除重复的逗号分隔数字
- javascript - 如何在 HTML 画布中对齐文本?
- sapui5 - 不显示带有 CDSView 注释的 SAPUI5 SmartChart
- javascript - 动态 CSS 内容
- javascript - 我正在编写一个正则表达式来处理以下内容,但我被困在两者之间