【问题标题】:How to remove All posts and Single User using Mongodb and Node.js如何使用 Mongodb 和 Node.js 删除所有帖子和单个用户
【发布时间】:2021-09-24 03:07:40
【问题描述】:

我有点卡在某事上,我正在开发一个个人博客,该博客使用 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.js mongodb express


    【解决方案1】:

    我建议直接使用deleteOnedeleteMany 而不是使用find

    【讨论】:

    • 所以像 Post.deletemany({creator: userId}).then(result => { User.findbyIdAndDelete(userId).then().catch() ?那是正确的方法吗?链接承诺?我对如何链接它们有点困惑,我应该先删除帖子,如果成功,然后删除用户,还是相反?或者这两种方法都没有区别?跨度>
    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 2017-07-03
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多