In this tutorial I'm going to explain how to develop restful apis node js. I will be using MongoDB as database. I will be explaining simple apis which can add,fetch all, fetch by id, delete or destroy and update the records.
To start with we need to install mongoose by following command if we have not installed it yet.
To install the mongoose:
1
|
npm install mongoose
|
Here is the post route which contains all functions add,fetch all, fetch by id, delete or destroy and update the records.
routes/post.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
var express = require('express');
var router = express.Router();
var Post = require('../schema/post');
var Response = require('../common/response');
/* ADD POST. */
router.post('/add-post', function(req, res, next) {
var data = new Post(req.body);
data.save(function(err){
if(err){
Response.errorResponse(err,res);
}else{
Response.successResponse('Received!',res,{});
}
})
});
/* GET ALL POSTS. */
router.get('/get-all', function(req, res, next) {
Post.find({}, function(err, posts) {
if(err){
Response.errorResponse(err,res);
}else{
Response.successResponse('Post Listing!',res,posts);
}
});
});
/* GET SINGLE POST BY ID */
router.get('/get-by-id/:id', function(req, res, next) {
Post.findById(req.params.id, function (err, post) {
if(err){
Response.errorResponse(err,res);
}else{
Response.successResponse('Post Detail!',res,post);
}
});
});
/* DELETE POST BY ID */
router.delete('/destroy', function(req, res, next) {
Post.findByIdAndRemove(req.body._id, function (err, post) {
if (err) {
Response.errorResponse(err,res);
} else {
Response.successResponse('Post deleted!',res,{});
}
});
});
/* UPDATE POST */
router.put('/update-post', function(req, res, next) {
console.log(req.body._id);
Post.findByIdAndUpdate(req.body._id, req.body, function (err, post) {
if (err) {
Response.errorResponse(err,res);
} else {
Response.successResponse('Post updated!',res,{});
}
});
});
module.exports = router;
|
MongoDB connection using mongoose with node JS:
Here I am creating connection with MongoDB by using mongoose.
Write the following code in app.js
1
2
3
4
5
6
7
|
// DB connection
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/my_database', { useMongoClient: true })
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
// DB connection end
|
Add route in app.js also:
1
|
app.use(require('./routes'));
|
Create a new route file in main directory:
routes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
|
var express = require('express');
var router = express.Router();
var routes = require('./routes/index');
var users = require('./routes/users');
var post = require('./routes/post');
router.use('/', routes);
router.use('/users', users);
router.use('/post', post);
module.exports = router;
|
Create schema for blog post:
schema/post.js
Here I'm defining schema for posts in MongoDB or in terms of MongoDB I'm defining collection here.
1
2
3
4
5
6
7
8
9
10
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var BlogPost = new Schema({
name :String,
email :String,
mobile :Number,
message :String
},{ strict: false });
module.exports = mongoose.model('Post', BlogPost);
|
Response :
common/response.js
This file is used to return the json response in a format. Here I have created two functions errorResponse is to return the error response and successResponse is to return the success response in json format.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
module.exports = {
errorResponse: function(err,res) {
res.status(err.status || 500);
res.end(JSON.stringify({
message: err.message,
error: err,
status: 0
}));
},
successResponse: function(message,res,data) {
res.status(200);
res.end(JSON.stringify({
message: message,
data: data,
status: 1
}));
}
}
|
You can download the web services node js code from here.