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"
});
});
};
0 comments:
Post a comment