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

mongoose-crud #18

Open
wants to merge 1 commit 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
55 changes: 55 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
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 mongoose = require('mongoose');

var index = require('./routes/index');
var users = require('./routes/users');
var books = require('./routes/books.routes');
var customer = require('./routes/customer.routes');
var transaction = require('./routes/transcation.routes');

mongoose.connect('mongodb://localhost:27017/library');

var app = express();

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

// 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);
app.use('/api/users', users);
app.use('/api/books', books);
app.use('/api/customer', customer);
app.use('/api/transaction', transaction);

// 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')('mongoose-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);
}
55 changes: 55 additions & 0 deletions controllers/books.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const BooksModel = require('../models/books.model')

module.exports = {
showBook(req,res) {
BooksModel.find()
.then(data => {
res.status(200).json({
message: "Success Show Data",
data
})
})
},
insertBook(req,res) {
let item = {
isbn: req.body.isbn,
title: req.body.title,
author: req.body.author,
category: req.body.category,
stock: req.body.stock
}

let data = new BooksModel(item)
data.save((err,data) => {
if(err) res.status(500).json({message: "Failed Insert Data"})
res.status(201).json({
message: "Insert Success",
data
})
})
},
updateBook(req,res) {
BooksModel.findOneAndUpdate(req.params.id, req.body, function (err, data) {
if (err) return res.send(500, { error: err })
res.status(201).json({
message: "Update Success",
data
})
})
},
deleteBook(req,res) {
BooksModel.remove({
_id: req.params.id
})
.then(data => {
res.status(200).json({
data
})
})
.catch(err => {
res.status(500).json({
message: "Failed Delete Data"
})
})
}
}
54 changes: 54 additions & 0 deletions controllers/customer.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const CustomerModel = require('../models/customer.model')

module.exports = {
showCustomer(req,res) {
CustomerModel.find()
.then(data => {
res.status(200).json({
message: "Success Show Data",
data
})
})
},
createCustomer(req,res) {
let user = {
name: req.body.name,
memberid: req.body.memberid,
address: req.body.address,
zipcode: req.body.zipcode,
phone: req.body.phone
}
let data = new CustomerModel(user)
data.save((err, success) => {
if (err) res.status(500).json({ message: "Failed Create Customer" })
res.status(201).json({
message: "Create Success",
data
})
})
},
updateCustomer(req,res) {
CustomerModel.findOneAndUpdate(req.params.id, req.body, function (err, data) {
if (err) return res.send(500, { error: err })
res.status(201).json({
message: "Update Success",
data
})
})
},
deleteCustomer(req,res) {
CustomerModel.remove({
_id: req.params.id
})
.then(data => {
res.status(200).json({
data
})
})
.catch(err => {
res.status(500).json({
message: "Failed Delete Data"
})
})
}
}
86 changes: 86 additions & 0 deletions controllers/transaction.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
let transactionModel = require('../models/transaction.model')

module.exports = {
createTransaction(req,res) {
var addDate = new Date();
addDate.setDate(addDate.getDate() + Number(req.body.days));

let addObj = {
member: req.body.member,
days: req.body.days,
out_date: new Date(),
due_date: addDate,
booklist: req.body.booklist
}

let data = new transactionModel(addObj)

data.save((err, success) => {
if (err) res.status(500).json({ message: "Failed Create Transaction" })
res.status(201).json({
message: "Create Transaction Success",
data
})
})
},
returnTransaction(req,res) {
transactionModel.findOne({
_id: req.params.id
})
.then(getData => {
// console.log(req.params.id)
// console.log(req.body.in_date)
let adjusFine = req.body.in_date * 1000

let inDate = getData.due_date
inDate.setDate(inDate.getDate() + Number(req.body.in_date))

let editData = {
fine: adjusFine,
in_date: inDate
}
transactionModel.findByIdAndUpdate(req.params.id, editData, function (err, data) {
if (err) return res.send(500, { error: err })
res.status(201).json({
message: "Update Success",
data
})
})
console.log(editData)
// console.log(inDate.getDate() + req.body.in_date)
})
.catch(err => {
console.log(err)
})
},
showTransaction(req, res) {
transactionModel.find()
.populate('member')
.populate('booklist')
.exec()
.then(data => {
res.status(200).json({
message: "Success Show Data",
data
})
})
.catch(err => {
console.log(err)
})
},
deleteTransaction(req,res) {
transactionModel.remove({
_id: req.params.id
})
.then(data => {
res.status(200).json({
data
})
})
.catch(err => {
res.status(500).json({
message: "Failed Delete Data"
})
})
}
}
12 changes: 12 additions & 0 deletions models/books.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var bookSchema = new Schema({
isbn: String,
title: String,
author: String,
category: String,
stock: Number
})

module.exports = mongoose.model('books', bookSchema)
12 changes: 12 additions & 0 deletions models/customer.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var customerSchema = new Schema({
name: String,
memberid: String,
address: String,
zipcode: Number,
phone: Number
})

module.exports = mongoose.model('customer', customerSchema)
Loading