.pre和简单查询猫鼬的区别



const deletePost = async (req, res) => {
const deleteComments = await Comment.deleteMany({ post: req.params.postId });
const deletedPost = await Post.findOneAndDelete({
$and: [{ _id: req.params.postId }, { user: req.user }],
});
res.json(deletedPost);
};

const deletePost = async (req, res) => {
const deletedPost = await Post.findOneAndDelete({
$and: [{ _id: req.params.postId }, { user: req.user }],
});
res.json(deletedPost);
};

+ post model

postSchema.pre("findOneAndDelete", async function () 
const deleteAssociatedComments = await Comment.deleteMany({ post: postId });
);

为什么我要在模型中使用。pre而不是在deletePost函数中运行查询?

Pre和Post被称为钩子,它类似于express中的中间件概念,它们是在函数执行过程中被执行的函数。

Pre在方法调用前执行,Post在方法完成后执行。

如果你想用更多的功能修饰一个现有的方法,你应该使用pre和post,如果你正在创建一个自定义查询,你应该使用查询语法,如果你想在一个操作成功后运行级联操作,这些钩子可以工作。

最新更新