【发布时间】:2021-02-26 15:57:38
【问题描述】:
在我的 Nodejs 和 Express 应用程序中,我有一个 mongoose 用户模式、一个帖子模式和一个评论模式,如下所示:
const UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true
},
password: String,
posts : [
{
type : mongoose.Schema.Types.ObjectId,
ref : 'Post'
}
]
});
const PostSchema = new Schema({
author : {
type : mongoose.Schema.Types.ObjectId,
ref : 'User'
},
createdAt: { type: Date, default: Date.now },
text: String,
comments : [
{
type : mongoose.Schema.Types.ObjectId,
ref : 'Comment'
}
],
});
const CommentSchema = new Schema({
author : {
type : mongoose.Schema.Types.ObjectId,
ref : 'User'
},
createdAt: { type: Date, default: Date.now },
text: String
});
我已经为我的用户编写了一般的 CRUD 操作。删除我的用户时,我可以使用 deleteMany 轻松删除与该用户关联的所有帖子:
Post.deleteMany ({ _id: {$in : user.posts}});
要删除所有已删除帖子的所有 cmets,我可能可以遍历帖子并删除所有 cmets,但我查看了 mongoose 文档here,似乎 deleteMany 函数触发了deleteMany 中间件。所以在我的 Post 架构中,我在定义架构之后和导出模型之前添加了以下内容。
PostSchema.post('deleteMany', async (doc) => {
if (doc) {
await Comment.deleteMany({
_id: {
$in: doc.comments
}
})
}
})
删除用户时,会触发此中间件,但不会删除 cmets。我使用 console.log(doc) 获得了 doc 的价值,但我认为它不包括我打算做的事情所需的内容。有人可以告诉我如何正确使用 deleteMany 中间件,或者如果这不是正确的路径,当我删除用户及其帖子时,删除所有关联 cmets 的最有效方法是什么?
【问题讨论】:
标签: node.js express mongoose middleware mongoose-schema