node.js - 如何使用 mongoose 和 nodejs 删除嵌套在 Post 模式中的评论?
问题描述
我希望能够删除我的 Post 模型中的评论。
这是我的 Post 模型架构:
const PostSchema = new Schema({
userID: {
type: Schema.Types.ObjectId,
ref: 'user'
},
content: {
type: String,
required: true
},
registration_date: {
type: Date,
default: Date.now
},
likes: [
{
type: Schema.Types.ObjectId,
ref: "user"
}
],
comments: [
{
text: String,
userID: {
type: Schema.Types.ObjectId,
ref: 'user'
}
}
]
})
我有这条路线:
router.delete('/comment/:id/:comment_id', auth, async (req, res) => {
const postId = req.params.id
const commentId = req.params.comment_id
}
帖子中的评论如下所示:
comments: [
{
_id: 5f1df4cf5fd7d83ec0a8afd8,
text: 'comment 1',
userID: 5efb2296ca33ba3d981398ff
},
{
_id: 5f1df4d35fd7d83ec0a8afd9,
text: 'commnet 2',
userID: 5efb2296ca33ba3d981398ff
}
]
我想删除评论,不知道怎么做。有谁知道该怎么做?
解决方案
首先我们找到帖子,然后我们从评论数组中findByIdAndUpdate
删除评论。$pull
router.delete("/comment/:id/:comment_/id", async function (req, res) {
try {
const post = await Post.findByIdAndUpdate(
req.params.id,
{
$pull: { comments: {_id:req.params.comment_id}},
},
{ new: true }
);
if (!post) {
return res.status(400).send("Post not found");
}
} catch (err) {
console.log(err);
res.status(500).send("Something went wrong");
}
});
推荐阅读
- python - 删除重复的列
- typo3 - TYPO3 Xdebug PhpStorm
- android - 捏以缩放 MyTextureView 只是屏幕尺寸(宽度,高度)
- python - 我不断收到类型错误,不知道为什么
- java - 为什么尝试启动 MC 无法下载文件时出现此错误。minecraftforge-9.11.1.1345.jar?
- node.js - 使用 Sequelize 如何获得最接近该对象半径内的纬度和经度的 n 个元素?
- bash - 用连续的数字重命名文件,保留原始文件名
- fortran - 在 fortran 写入中转义引号并删除双换行符
- matplotlib - 为matplotlib中的每个plt.plot添加平均线?
- python - 仍然不知道如何模拟导入的库 - Python