Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix deleteOne() function of a mongoose model when it does not delete by req.params.id?

Firstly to be mentioned, I'm absolutely new to Node.Js and MongoDB.

I'm coding a back end API with Node.Js and MongoDB which will deal with GET, POST, DELETE requests from the front end, quite simple stuff.

I'm stuck while working with DELETE functionality.

Here is my posts.service.ts file contains this deletePost() function which sends the postId to the back end app.js file.

`

deletePost(postId: string) {
    this.http.delete('http://localhost:3000/api/posts/' + postId)
    .subscribe(() => {
      console.log(postId);
      console.log('Deleted');
    });
  }

`

I have added this console.log(postId) to check whether it is actually containing the actual postId and found that it does. I have also matched it with the real Id in MongoDB by checking through mongo shell.

Here is the delete() function in the back end app.js file that should do the actual task.

`

app.delete("/api/posts/:id", (req, res, next) => {
  Post.deleteOne({ _id: req.params.id }).then(result => {
    console.log(result);
    res.status(200).json({message: "Post deleted"});
  });
});

`

The console.log(result) line should print some result in the terminal, but it does not, so does not it delete the collection in the DB.

I`m running this on an Ubuntu 16.04 LTS pc.

Some clue would mean great help. Thank you very much for your kind effort.

like image 711
Ratnadeep Avatar asked Feb 18 '19 03:02

Ratnadeep


1 Answers

deleteOne doesn't return the deleted document. It always deletes the first matching document and return the number of documents deleted with the boolean value.

From the mongodb docs deleteOne:

Returns:

  1. A document containing: A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled

  2. deletedCount containing the number of deleted documents

From the mongoose docs

Deletes the first document that matches conditions from the collection. Behaves like remove(), but deletes at most one document regardless of the single option.

like image 79
Ashh Avatar answered Nov 19 '22 04:11

Ashh