【问题标题】:How to delete all documents from mongoDB using deleteMany()?如何使用 deleteMany() 从 mongoDB 中删除所有文档?
【发布时间】:2021-08-19 07:08:42
【问题描述】:

我正在尝试使用 Express + MongoDB 构建 React 应用程序。

我能够使用 POST 方法成功地将一些文档发布到 MongoDB,但我无法弄清楚如何使用 DELETE 删除所有文档(我试图在数据库中拥有一个文档而不是它们的列表)。

这些是我的路线:

router.post('/totalbalance', (request, response) => {
    const totalBalance = new TotalBalanceModelTemplate({
        totalBalance:request.body.totalBalance,
    });
    totalBalance.save()
    .then(data => {
        response.json(data);
    })
    .catch(error => {
        response.json(error);
    });
});

router.delete('/totalbalance', (request, response) => {
    request.body.totalBalance.deleteMany({}, function(err) {
        if (err) {
            response.status(500).send({error: "Could not clead database..."});           
        } else {
            response.status(200).send({message: "All info was deleted succesfully..."});
        }
    });
});

这些是 axios 请求:

axios.post('http://localhost:4000/app/totalbalance', 
 {
        totalBalance: newTotalBalance
 });

useEffect(() => {
    axios.delete('http://localhost:4000/app/totalbalance')
        .then(res => {
            console.log('request here ', res);
        })
        .catch(function (error) {
            console.log(error);
        })
}, []);

当我启动应用程序时,在 Chrome 控制台中我看到错误“xhr.js:177 DELETE http://localhost:4000/app/totalbalance 500 (Internal Server Error)”(这是因为我使用了 useEffect()传递一个空数组作为依赖,所以它在 React 组件的初始渲染后运行一次。

DELETE应该怎么做? 也许我应该结合使用 POST 和 DELETE 方法?

【问题讨论】:

    标签: reactjs mongodb http axios http-delete


    【解决方案1】:

    您需要在 Mongoose 模型上调用 deleteMany 函数。 request.body.totalBalance 不是模特。

    看起来您需要.delete 路由如下。

    router.delete('/totalbalance', (request, response) => {
        TotalBalanceModelTemplate.deleteMany({}, function(err) {
            if (err) {
                response.status(500).send({error: "Could not clead database..."});           
            } else {
                response.status(200).send({message: "All info was deleted succesfully..."});
            }
        });
    });
    

    【讨论】:

    • @grubbyGerbil - 太棒了。乐意效劳。祝你的编码之旅好运!
    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 2014-09-23
    • 2014-05-19
    • 2021-03-10
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多