CRUD operations using NodeJS + Express + MongoDB
I'll start this tutorial by keeping in mind that you already know the basics of NodeJS.
If you are not installed NodeJS on your machine, please go ahead and install the latest version first. The following tutorial shows you how to install on Ubuntu machines
Project Setup
Once you installed NodeJS, open terminal and create a folder with name nodejs-mongodb-crud
and move to that folder by running following series of commands
mkdir nodejs-mongodb-crud
cd nodejs-mongodb-crud
Now create a new node project by running the following command.
npm init --yes
This creates you a package.json
file.
Now start adding required dependencies by running following command
npm install express body-parser mongodb co --save
Now if you look at your packages.json
file, it should look like following
{
"name": "nodejs-mongodb-crud",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.2",
"co": "^4.6.0",
"express": "^4.16.2",
"mongodb": "^3.0.3"
}
}
Now you are ready with the setup, lets start writing our index.js
and add the basic CRUD routes.
Create the index.js
file and put the following content
index.js
var express = require('express');
var bodyParser = require('body-parser');
var co = require('co')
var app = express();
var co = require('co');
var MongoClient = require('mongodb').MongoClient;
Long = require('mongodb').Long;
// Express Configurations
app.use(bodyParser.urlencoded({
limit: "5mb",
extended: false
}));
app.use(bodyParser.json({limit: "5mb"}));
app.set('port', (process.env.PORT || 8080));
// Mongo
db = {};
var mongoDbUri = 'mongodb://localhost:27017/nodejs-mongodb-crud-db'
var settings = {
reconnectTries : Number.MAX_VALUE,
autoReconnect : true
};
MongoClient.connect(mongoDbUri, settings, function(err, dbref) {
if (!err) {
db = dbref.db('nodejs-mongodb-crud-db');
addRouts();
console.log("Mongodb connected");
}
});
app.post('/user', function(req, res){
co(function*() {
yield db.collection('users').save(req.body)
res.send('Created')
}).catch(function(err) {
console.log(err.stack)
res.status(500).send(err)
})
})
// read
app.get('/user/:id', function(req, res){
var id = req.params.id
co(function*() {
var userObj = yield db.collection('users').findOne({_id:id})
res.send(userObj)
}).catch(function(err) {
console.log(err.stack)
res.status(500).send(err)
});
});
// update
app.put('/user', function(req, res){
co(function*() {
yield db.collection('users').save(req.body)
res.send('Updated')
}).catch(function(err) {
console.log(err.stack)
res.status(500).send(err)
})
})
// delete
app.delete('/user/:id', function(req, res){
var id = req.params.id
co(function*() {
yield db.collection('users').deleteOne({_id:id});
res.send('Deleted Successfully')
}).catch(function(err) {
console.log(err.stack)
res.status(500).send(err)
})
})
// Start App
app.listen(app.get('port'), function() {
console.log('Node app is running on port: ', app.get('port'));
});
Starting Node Application
Now start the application by running following command
node index.js
After successful start you should see logs like below
$ node index.js
Node app is running on port: 8080
Mongodb connected
Testing CRUD operations
Now lets start testing the CRUD operations with curl commands
Create
curl -X POST \
http://localhost:8080/user \
-H 'content-type: application/json' \
-d '{
"_id" : "E-001",
"name" : "Test Name 1",
"age" : 20,
"email" : "[email protected]"
}'
Read
curl -X GET \
http://localhost:8080/user/E-001
Update
curl -X PUT \
http://localhost:8080/user \
-H 'content-type: application/json' \
-d '{
"_id" : "E-001",
"name" : "Test Name 2",
"age" : 22,
"email" : "[email protected]"
}'
Delete
curl -X DELETE \
http://localhost:8080/user/E-001