首页 > 解决方案 > 如何使用 Mongodb 和 Node.js 删除所有帖子和单个用户

问题描述

我有点卡在某事上,我正在开发一个使用 mongodb 和 node.js 和 express 的全栈个人博客。在该博客网站中,只有一个用户可以注册,并且所有帖子都与该用户相关联。我正在使用 REST API 创建一个控制器,该控制器可以删除用户以及所有帖子。我有可用的用户和帖子对象,我想知道是否有一种方法可以使用用户和帖子模式对象来删除用户和所有帖子。我不想使用 db.collection('posts') 东西,因为我没有在其他任何地方使用过。我浏览了 mongodb node.js 驱动程序文档,但我仍然不知道该怎么做。

    exports.deleteUser = (req, res, next) => {

    User.find().then(user => {
        //what do i do here?
    })
    .catch(err => {
        if (!err.statusCode) {
            err.statusCode = 500;
        }
        // you need to do next() otherwise error will not reach
        // our middlewear in app.js file
        next(err);
    })

    Post.find().then(allPosts => {
        if (!allPosts) {
            //what do i do here?
        }
        
        res.status(200).json({message: message})
    })
    .catch(err => {
        if (!err.statusCode) {
            err.statusCode = 500;
        }
        // you need to do next() otherwise error will not reach
        // our middlewear in app.js file
        next(err);
    })
}

标签: node.jsmongodbexpress

解决方案


我建议直接使用deleteOneanddeleteMany而不是使用find.


推荐阅读