0

this is my route .js delete function

//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);
        }
    });
});

my have api like this,

{
  "success": true,
  "forums": [
    {
      "createdAt": "2018-11-24T07:00:58.716Z",
      "_id": "5bf8f907f6108603f4eb8c28",
      "title": "how to chs right prgm",
      "body": "zxsdcfghj",
      "createdBy": "[email protected]",
      "answers": [
        {
          "createdAt": "2018-11-24T07:00:58.716Z",
          "_id": "5bf8f939f6108603f4eb8c29",
          "content": "asdfghjmksadfghjk",
          "createdBy": "[email protected]"
        }
      ],
      "__v": 1
    }
  ]
}

i want to delete that particular answer id, but my delete function , delete question also . i don't know where i did mistake please help me.

2 Answers 2

4

You used Forum.findOneAndDelete() so of course it will find one forum and delete it. If you want to delete only answer you need to find forum then pull answer from forum then save forum. So your answer will be deleted from forum. Like this

let forum = await Forum.findOne({_id: req.params.id})
if (forum) {
  forum.answers.pull({_id: req.params.answerId})
  await forum.save()
}

Or this

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)
})
Sign up to request clarification or add additional context in comments.

4 Comments

if i use findOne that delete function is not working.
well I forgot to add await at .findOne() function. I've fixed it now it will work properly.
sry i didn't use await , if i use that i get error like " await is only valid in async function" .
you need to use it inside async function which you can make your callback to async. router.delete('/:id/deleteans/:answersId', (req, res, next) => { to router.delete('/:id/deleteans/:answersId', async (req, res, next) => { or you can use then instead. I've edited my answer to add .then() version
0
let result = await Model.update({typeOf: docs.typeOf}, {"$pull": {$pull: {answers: {_id: req.params.answerId}  } } , {safe: true}).lean();

Hope this works...

1 Comment

i can't understand 'typeOf: docs.typeOf' , this one how i implement in node js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.