node.js - 如何使用 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);
})
}
解决方案
我建议直接使用deleteOne
anddeleteMany
而不是使用find
.
推荐阅读
- java - 在 Java 中将字符串集合复制到另一个字符串的时间复杂度
- c# - Unity C#:如何将消息从一个应用程序发送到不同 IP 上的另一个应用程序?
- python - 在运行 Sophos 的机器上,为什么我的所有浏览器都无法从我的 Python 应用程序实时接收服务器发送的事件 (sse)?
- java - HTTP请求是POST请求,xxl-job参数是GET,为什么要执行
- python - 在保持梯度值的同时重复张量元素
- javascript - 处理动态表以在 Vuejs 框架中添加和删除行,下面是我的表
- php - 检索新的数据库记录
- reactjs - 获取发送空的帖子参数 - 反应原生
- c# - 使用图像路径显示图像不起作用
- django - django inlineformset 中的动态额外字段