Reactjs 如何使用deleteMany()从mongoDB中删除所有文档?
我正在尝试使用Express+MongoDB building React应用程序 我能够使用post方法成功地将一些文档发布到MongoDB,但我不知道如何使用delete删除所有文档(我试图在DB中有一个文档,而不是它们的列表) 以下是我的路线:Reactjs 如何使用deleteMany()从mongoDB中删除所有文档?,reactjs,mongodb,http,axios,http-delete,Reactjs,Mongodb,Http,Axios,Http Delete,我正在尝试使用Express+MongoDB building React应用程序 我能够使用post方法成功地将一些文档发布到MongoDB,但我不知道如何使用delete删除所有文档(我试图在DB中有一个文档,而不是它们的列表) 以下是我的路线: router.post('/totalbalance', (request, response) => { const totalBalance = new TotalBalanceModelTemplate({ to
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 DELETEhttp://localhost:4000/app/totalbalance 500(内部服务器错误)”
如何删除?
也许我应该将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..."});
}
});
});
成功了!非常感谢@grubbyGerbil-太棒了。很乐意帮忙。祝你的编码之旅好运!