如何使用 deleteMany() 从 mongoDB 中删除所有文档?

问题描述

我正在尝试使用 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',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(内部服务器错误)”(这是因为我使用 useEffect()传递一个空数组作为依赖,所以它在 React 组件初始渲染后运行一次)。

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

解决方法

您需要在 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..."});
        }
    });
});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...