HTTP Methods for RESTful Services with Examples (Mongoose)

The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively.

POST – Create

This is how we can create new items in the database. This will commonly be from an HTTP POST request, although you can do this anywhere you want


var article = new Article(req.body);
article.save((err, article) => {
  if (err) {
    res.status(500).send(err);
  }
  res.status(200).send(article);
});

GET – Read

Here the example like, how HTTP get method are typically used in a RESTful API:

1. Finds all documents in the database that match the query. If no query is given, it returns everything.


Article.find((err, articles) => {
  if (err) {
    res.status(500).send(err);
  } else {
    res.status(200).send(articles);
  }
});

2. Finds particular document in the database that match the query.


Article.find({"title": "lorem ipsum"}, (err, people) =>{
  if (err) {
    res.status(500).send(err)
  } else {
    res.status(200).send(articles);
  }
});

Note: Mongoose gives us 3 basic ways to get data from the database such as .find(), .findOne(), and .findById()

PUT – Update

The PUT will overwrite the existing object with whatever you sent in your request body. For Example, I had an object like this: { name: “Andrew”, age: 32}, a PUT request with the following data: { name: “andrew” } would completely overwrite the original object and result in just { name: “Smith” } with no age property.

DELETE – Delete

Removes this document from the collection.


Article.remove({ _id: req.body.id }, function(err) {
  if (!err) {
    message.type = 'notification!';
  } else {
    message.type = 'error';
  }
});

Note: Mongoose v4.0 introduced some helper methods - .findOneAndRemove() and .findByIdAndRemove()

PATCH:
The PATCH request will update certain part of an existing object. And also it saves new data what you submitted and leaving old data.

Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkedin
Share On Pinterest

Be the first to comment

Leave a Reply

Your email address will not be published.

*


*