Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mongodb-crud #10

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,11 @@
# mongodb-crud
# mongodb-crud

list of Book Route :

| Route | HTTP | Description |
| ------------- | ------ | ---------------------------- |
| /api/book | GET | Show All Data book |
| /api/book/:id | GET | Show Data book by ObjectID |
| /api/book | POST | Added data book |
| /api/book/:id | PATCH | Update data book by ObjectID |
| /api/book/:id | DELETE | Delete data book by ObjectID |
44 changes: 44 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;
90 changes: 90 additions & 0 deletions bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env node

/**
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('mongodb-crud:server');
var http = require('http');

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

var server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
102 changes: 102 additions & 0 deletions controllers/booksController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
var MongoClient = require('mongodb');
// Connection URL
var url = 'mongodb://localhost:27017/mongodb-crud';

var methode = {}

methode.insert = (req, res, next) =>{
MongoClient.connect(url, function(err, db) {
console.log("Connected successfully to server");
var bookCollection = db.collection('books');
// Insert some documents
bookCollection.insertOne({
isbn : req.body.isbn,
title : req.body.title,
author : req.body.author,
category : req.body.category,
stock : req.body.stock
}
, function(err, result) {
res.send("Inserted book into the library")
});
});
}

methode.find = (req, res, next)=>{
MongoClient.connect(url, (err, db) => {
console.log("Connected successfully to server");
var findBook = function(db, callback){
var bookCollection = db.collection('books');
bookCollection.find({}).toArray(function(err, docs) {
console.log("Found the following records");
res.send(docs)
callback(docs);
});
}
findBook(db, () =>{
db.close();
})
})
}

methode.findOne = (req, res, next)=>{
MongoClient.connect(url, (err, db) => {
console.log("Connected successfully to server");
var findBook = function(db, callback){
var bookCollection = db.collection('books');
bookCollection.find({_id : new MongoClient.ObjectId(req.params.id)}).toArray(function(err, docs) {
console.log("Found the following records");
res.send(docs)
callback(docs);
});
}
findBook(db, () =>{
db.close();
})
})
}

methode.edit = (req, res, next) =>{
MongoClient.connect(url, function(err, db) {
console.log("Connected successfully to server");
var updateBook = function(db, callback) {
// Get the documents collection
var bookCollection = db.collection('books');
// Insert some documents
bookCollection.updateOne({
_id : new MongoClient.ObjectId(req.params.id)
},{ $set: {
isbn : req.body.isbn,
title : req.body.title,
author : req.body.author,
category : req.body.category,
stock : req.body.stock}}
, function(err, result) {
res.send("Updated book into the library")
});
}
updateBook(db, function() {
db.close();
});
});
}

methode.remove = (req, res, next) => {
MongoClient.connect(url, function(err, db){
console.log("Connected successfully to server");
// var removeDocument = function(db, callback) {
// Get the documents collection
var collection = db.collection('books');
collection.deleteOne({ _id : new MongoClient.ObjectId(req.params.id) });
res.send("delete sucsess")
db.close();
// }
// removeDocument(db, function() {
// db.close();
// });
})
}

module.exports = methode

// Use connect method to connect to the server
18 changes: 18 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "mongodb-crud",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "nodemon ./bin/www"
},
"dependencies": {
"body-parser": "~1.17.1",
"cookie-parser": "~1.4.3",
"debug": "~2.6.3",
"express": "~4.15.2",
"jade": "~1.11.0",
"mongodb": "^2.2.26",
"morgan": "~1.8.1",
"serve-favicon": "~2.4.2"
}
}
12 changes: 12 additions & 0 deletions routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var express = require('express');
var router = express.Router();
var booksController = require('../controllers/booksController')

/* GET home page. */
router.post('/api/books',booksController.insert);
router.get('/api/books',booksController.find);
router.get('/api/books/:id',booksController.findOne);
router.put('/api/books/:id',booksController.edit);
router.delete('/api/books/:id',booksController.remove);

module.exports = router;