我有一个User模型和BlogPost模型。用户模型存储一系列blogPost。我使用Model.deleteMany设置了一个预先的'findOneAndDelete'钩子,以删除与用户相关联的blogPosts,但它不起作用。 blogPosts数组中有1个帖子。
结果来自
await BlogPost.deleteMany({ _id: { $in: this.blogPosts } });
是
{ n: 0, ok: 1, deletedCount: 0 }
{ n: 0, ok: 1, deletedCount: 0 }
{ n: 0, ok: 1, deletedCount: 0 }
如果将钩子从'findOneAndDelete'更改为'remove',则使用相同的pre钩子,但不建议使用'remove'。
有什么想法吗?
用户架构
const UserSchema = new Schema({
name: {
type: String,
required: [true, 'Name is required'],
validate: {
validator(name) {
if (name.length > 2 && name.length < 10) {
return true;
}
return false;
},
message: () => `Name must be between 2 and 10 characters`
}
},
posts: [PostSchema],
likes: {
type: Number,
default: 0
},
blogPosts: [
{
type: Schema.Types.ObjectId,
ref: 'blogPost'
}
]
});
UserSchema.pre('findOneAndDelete', async function(next) {
const BlogPost = mongoose.model('blogPost');
const res = await BlogPost.deleteMany({ _id: { $in: this.blogPosts } });
next();
});
BlogPost模式
const BlogPostSchema = new Schema({
title: String,
content: String,
comments: [
{
type: Schema.Types.ObjectId,
ref: 'comment'
}
]
});
const user = await User.findOneAndDelete({ name: 'Ssam' });