node.js - 节点js删除数组数据的功能
问题描述
这是我的路线 .js 删除功能
//Delete the country info
router.delete('/:id/deleteans/:answersId', (req, res, next) => {
Forum.findOneAndDelete({_id:req.params.id},{$pull: {answers: {_id: req.params.answerId}} }, function (err, result) {
if (err) {
res.json(err);
}
else {
res.json(result);
}
});
});
我有这样的api,
{
"success": true,
"forums": [
{
"createdAt": "2018-11-24T07:00:58.716Z",
"_id": "5bf8f907f6108603f4eb8c28",
"title": "how to chs right prgm",
"body": "zxsdcfghj",
"createdBy": "induece94@gmail.com",
"answers": [
{
"createdAt": "2018-11-24T07:00:58.716Z",
"_id": "5bf8f939f6108603f4eb8c29",
"content": "asdfghjmksadfghjk",
"createdBy": "induece94@gmail.com"
}
],
"__v": 1
}
]
}
我想删除那个特定的答案 ID,但我的删除功能,也删除问题。我不知道我在哪里做错了请帮助我。
解决方案
您使用了 Forum.findOneAndDelete() 所以它当然会找到一个论坛并将其删除。如果您只想删除答案,您需要找到论坛然后从论坛中提取答案然后保存论坛。因此,您的答案将从论坛中删除。像这样
let forum = await Forum.findOne({_id: req.params.id})
if (forum) {
forum.answers.pull({_id: req.params.answerId})
await forum.save()
}
或这个
Forum.findOne({_id: req.params.id}).then((forum) => {
if (forum) {
forum.answers.pull({_id: req.params.answerId})
forum.save().then((result) => {
res.json(result)
}).catch((err) => {
res.json(err)
})
}
}).catch((err) => {
res.json(err)
})
推荐阅读
- github - 有没有办法使用 CircleCI 自定义 Github 检查?
- spring-boot - SpringBoot & Kotlin 可执行jar ClassNotFoundException
- c++ - 错误:'operator*' 不匹配(操作数类型为 'const llvm::DataLayout')
- amazon-ec2 - 管理 EC2 实例启动/关闭/休眠调度程序的最佳实践是什么?
- javascript - { ...obj1, obj2 } 究竟做了什么
- python - 如何在 YAML 配置文件中添加 TaskFormatter
- mysql - MySQL 中 BINARY LIKE 操作的索引
- javascript - 在带间隙的堆积面积图中渲染伪影
- exception - 如何在 Javacc 中操作 ParseException
- python - 从 numpy argmin 中删除轴参数,但仍然矢量化