SoftwareQuery
Home About Contact

REST API To Create CRUD Operation With Express.js and Node.js Using By MongoDB

 SoftwareQuery     No comments   


In this tutorial, we are talking about to HOW TO create a Rest API using Express js Node js with MongoDB to make a CRUD.Express.js is a framework of Node.js.It is a very lightweight framework and also easy to use.

MongoDB-: MongoDB has become one of the maximum popular NoSQL databases, being used because of the backend for plenty important websites consisting of eBay, Craigslist, SourceForge and The the big apple times. MongoDB is available below the GNU Affero preferred Public License whilst its language drivers are to be had below the Apache License. There are also industrial licenses being supplied.


Step-1: Firstly we are going to create directoryfdsff then we install the application.
                $ mkdir node-mongo-crud
                // now go to directory
                 cd node-mongo-crud

Step-2: After install application then we are going to create a package.json file using this command.

                                                     $ npm init 

Step-3: After creating the file we are going to install dependencies using npm command if you are run npm init command then ask following things.

        package name: (mongo-crud) node-mongo-crud-api
        version: (1.0.0) 
        description: Building a crud api using Node.js, Express, and Mongodb
        entry point: (index.js) server.js
        test command: 
        git repository: 
        keywords: Node.js Express Mongodb Tutorial Article Post Database
        author: expertphp.in
        license: (ISC) 
        About to write to /var/www/node-mongo-crud/package.json:

        {
       "name": "node-mongo-crud-api",
       "version": "1.0.0",
       "description": "Building a crud api using Node.js, Express, and Mongodb",
       "main": "server.js",
       "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1"
        },
       "keywords": [
       "Node.js",
       "Express",
       "Mongodb",
       "Tutorial",
        "Article",
        "Post",
       "Database"
        ],
       "author": "expertphp.in",
       "license": "ISC"
        }
Is this OK?  yes

see the application called server.js
Step-4: we are installing a package then install the dependencies using the command:
         $ npm install express body-parser mongoose --save
        --save option is used to save all the dependencies in the package.json file.

Step-5: we are making an entry pointing this application using to touch Linux command.
                                  $ touch server.js
                                                   directory structure :
                                                   node-easy-notes-app
                                                  └── node_modules/
                                                   └── package.json
                                                    └── server.js
Step-6: Weare creating a database configuration and also make a directory "config" inside the root directory of the application config file.

        $ mkdir config
        $ cd config
        $ touch database.config.js
        database.config.js
        const mongoose = require('mongoose');
        mongoose.Promise = global.Promise;
        mongoose.connect("mongodb://localhost:27017/demodatabase")
        .then(() => {
        console.log("Connection successfully established");    
        }).catch(err => {
        console.log('Could not connect to the database.');
        process.exit();

        }); 

Step-7: In this step, we are creating a Model schema then create a new directory "app" inside the root folder of the application we are creating another directory of the app folder by the command.
        $ mkdir -p app/models
        $ cd app/models
        $ touch categories.model.js
       Update the code in categories.model.js file :
       const mongoose = require('mongoose');
       const CategorySchema = mongoose.Schema({
       name: String,
       details: String
        },     {
       timestamps: true
       });

       module.exports = mongoose.model('Category', CategorySchema);
Step-8: We are Add the Routes the create a "routes" directory and also create a route file "category.route.js" in the routes directory.
       $ mkdir app/routes
       $ cd app/routes
      $ touch category.routes.js
      module.exports = (app) => {
     const category = require('../controllers/category.controller.js');
     app.post('/category', category.create);
    app.get('/category', category.findAll);
   app.get('/category/:categoryId', category.findOne);
   app.put('/category/:categoryId', category.update);
  app.delete('/category/:categoryId', category.delete);
}
Step-9: We are add routes in server.js then project want the server for REST API .
        const express = require('express');
        const bodyParser = require('body-parser');
        const dbConfig = require('./config/database.config.js');

        const app = express();

       //   parse requests of content-type - application/x-www-form-urlencoded
           app.use(bodyParser.urlencoded({ extended: true }))

      // parse requests of content-type - application/json
         app.use(bodyParser.json())

      // define a simple route
         app.get('/', (req, res) => {
          res.json({"message": "Welcome to ExpertPHP.in"});
       });

       require('./app/routes/category.routes.js')(app);
      // listen for requests
      app.listen(3000, () => {
      console.log("Node JS Server running on port 3000");

     });
Step-10:  We are going to add controller then create controller directory with the app and also controller file "category.controller.js" using by directory command.
           $ mkdir app/controllers
           $ cd app/controllers
           $ touch category.controller.js


        const Category = require('../models/category.model.js');

       // Create and Save a  Category
         exports.create = (req, res) => {

          };

       // Retrieve and return all categories from the database.
         exports.findAll = (req, res) => {

          };

        // Find a single category with a id
         exports.findOne = (req, res) => {

          };

       // Update a category identified by the id in the request
         exports.update = (req, res) => {

          };

         // Delete a category with the specified categoryId in the request
         exports.delete = (req, res) => {

            };
              we are implement controller function  :
              Add new category :
             exports.create = (req, res) => {
if(!req.body.name) {
        return res.status(400).send({
            message: "Fields can not be empty"
        });
    }

    // Create a Category
    const category = new Category({
        name: req.body.name, 
        details: req.body.details
    });

    // Save Category in the database
    category.save()
    .then(data => {
        res.send(data);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Something went wrong."
        });
    });
};


List all category :
exports.findAll = (req, res) => {
Category.find()
    .then(categories => {
        res.send(categories);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Something went wrong."
        });
    });
};


Get a single category
exports.findOne = (req, res) => {
Category.findById(req.params.categoryId)
    .then(category => {
        if(!category) {
            return res.status(404).send({
                message: "Category does not exist"
            });            
        }
        res.send(category);
    }).catch(err => {        
        return res.status(500).send({
            message: "Something went wrong."
        });
    });
};


Update category :
exports.update = (req, res) => {
if(!req.body.name) {
        return res.status(400).send({
            message: "Fields can not be empty"
        });
    }
     // Find category and update it with the request body
    Category.findByIdAndUpdate(req.params.categoryId, {
        name: req.body.name,
        details: req.body.details
    }, {new: true})
    .then(category => {
        if(!category) {
            return res.status(404).send({
                message: "Category does not exist"
            });
        }
        res.send(category);
    }).catch(err => {        
        return res.status(500).send({
            message: "Something went wrong"
        });
    });
};


Delete category :
exports.delete = (req, res) => {
Category.findByIdAndRemove(req.params.categoryId)
    .then(category => {
        if(!category) {
            return res.status(404).send({
                message: "Category does not exist"
            });
        }
        res.send({message: "Category deleted successfully!"});
    }).catch(err => {      
        return res.status(500).send({
            message: "Something went wrong"
        });
    });
}; 



  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to TwitterShare to Facebook
Newer Post Older Post Home

0 comments:

Post a comment

Donate

Translate

Popular Posts

  • How to Make Image Upload Code Using AJAX
    Direct Copy Paste PHP File  Image Upload Code -   <html> <head> <meta charset="utf-8"> <meta http-equi...
  • Best Useful Free Plugin to Make Wordpress Theme
    Meta Slider   - Meta Slider is that the initial free possibility on today’s list. A premium version is additionally obtainable...
  • How To Install Magento on Localhost XAMPP OR WAMP SERVER
      Step-1 => Make Sure you have to install Latest Version of  Xampp server or Wamp server in your PC.   Step -2 => Go to Web Bro...
  • How To Intall Node.js Via Command On Window And Linux.
    Step-1 . Firstly We have to go official website of https://nodejs.org/en/ then download the latest version of Nodejs zi...
  • How to Set up Amazon Affiliate Marketing Account to Earn Money
    Amazon Associates is a  marketing of Amazon company. It is allowed to youtube channel owner, Social Media pages owner and any type...
  • How To Create Custom Pagination In WordPress
    Hello, Friend's in this post we are creating a custom code of Pagination in WordPress. It is very easy to put this code any custom...
  • How to create facebook share and like button for webpage
    Step-1 . Go to web browser type google and write facebook sharing button click this URL or open this URL.                     Ref URL:...
  • How To Scrape Data From Website Url Using Php.
    Q. why using a Scraping. If we want to get data of another website then using web scraping. It is using a PHP HTML Dom parser library ...
  • How To Install Wordpress in Xampp Server And Wamp Server
      Step 1st  -      Install WampServer or Xampp Server.                                                                               ...
  • Upload Multiple Images to Firebase Storage with Angular
    Step-1 . Create a new Angular Project open command window then write a command.                     #ng new UploadImageApp Step-2 ....

Home

This blog Is very help full for beginner coder,if you want to learn new things definitely this Blog is very
helpful for you guys.

Followers

Contact form

Name

Email *

Message *

Blog

  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Contact Us
  • Terms&Conditions

NewsLetter

Copyright © SoftwareQuery | Powered by softwarequery
Design by ShubhamTiwari | Theme by softwarequery.com | Distributed By softwarequery/