首页 > 解决方案 > 节点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,但我的删除功能,也删除问题。我不知道我在哪里做错了请帮助我。

标签: node.js

解决方案


您使用了 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)
})

推荐阅读