Skip to content

Commit e27df44

Browse files
committed
Nodejs Express MongoDB CRUD Example
1 parent b137613 commit e27df44

File tree

7 files changed

+1101
-0
lines changed

7 files changed

+1101
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = {
2+
url: 'mongodb+srv://loizenai:loizenai@cluster0.esvi3.mongodb.net/loizenaidb'
3+
}
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
const Customer = require('../models/customer.model.js');
2+
3+
// POST a Customer
4+
exports.create = (req, res) => {
5+
6+
const customer = new Customer({
7+
firstname: req.body.firstname,
8+
lastname: req.body.lastname,
9+
age: req.body.age,
10+
address: req.body.address,
11+
});
12+
13+
// Save a Customer in the MongoDB
14+
customer.save().then(data => {
15+
// send uploading message to client
16+
res.status(200).json({
17+
message: "Upload Successfully a Customer to MongoDB with id = " + data.id,
18+
customer: data,
19+
});
20+
}).catch(err => {
21+
res.status(500).json({
22+
message: "Fail!",
23+
error: err.message
24+
});
25+
});
26+
};
27+
28+
// FETCH all Customers
29+
exports.findall = (req, res) => {
30+
Customer.find().select('-__v').then(customerInfos => {
31+
res.status(200).json({
32+
message: "Get all Customers' Infos Successfully!",
33+
numberOfCustomers: customerInfos.length,
34+
customers: customerInfos
35+
});
36+
}).catch(error => {
37+
// log on console
38+
console.log(error);
39+
40+
res.status(500).json({
41+
message: "Error!",
42+
error: error
43+
});
44+
});
45+
};
46+
47+
// find a Customer by id
48+
exports.findone = (req, res) => {
49+
Customer.findById(req.params.id).select('-__v')
50+
.then(customer => {
51+
res.status(200).json({
52+
message: " Successfully Get a Customer from MongoDB with id = " + req.params.id,
53+
customer: customer
54+
});
55+
}).catch(err => {
56+
if(err.kind === 'ObjectId') {
57+
return res.status(404).send({
58+
message: "Customer not found with id " + req.params.id,
59+
error: err
60+
});
61+
}
62+
return res.status(500).send({
63+
message: "Error retrieving Customer with id " + req.params.id,
64+
error: err
65+
});
66+
});
67+
};
68+
69+
// UPDATE a Customer
70+
exports.update = (req, res) => {
71+
// Find customer and update it
72+
Customer.findByIdAndUpdate(
73+
req.params.id,
74+
{
75+
firstname: req.body.firstname,
76+
lastname: req.body.lastname,
77+
age: req.body.age
78+
},
79+
{new: true}
80+
).select('-__v')
81+
.then(customer => {
82+
if(!customer) {
83+
return res.status(404).send({
84+
message: "Error -> Can NOT update a customer with id = " + req.params.id,
85+
error: "Not Found!"
86+
});
87+
}
88+
89+
res.status(200).json({
90+
message: "Update successfully a Customer with id = " + req.params.id,
91+
customer: customer,
92+
});
93+
}).catch(err => {
94+
return res.status(500).send({
95+
message: "Error -> Can not update a customer with id = " + req.params.id,
96+
error: err.message
97+
});
98+
});
99+
};
100+
101+
// DELETE a Customer
102+
exports.delete = (req, res) => {
103+
let customerId = req.params.id
104+
105+
Customer.findByIdAndRemove(customerId).select('-__v -_id')
106+
.then(customer => {
107+
if(!customer) {
108+
res.status(404).json({
109+
message: "Does Not exist a Customer with id = " + customerId,
110+
error: "404",
111+
});
112+
}
113+
res.status(200).json({
114+
message: "Delete Successfully a Customer with id = " + customerId,
115+
customer: customer,
116+
});
117+
}).catch(err => {
118+
return res.status(500).send({
119+
message: "Error -> Can NOT delete a customer with id = " + customerId,
120+
error: err.message
121+
});
122+
});
123+
};
124+
125+
exports.filteringByAge = (req, res) => {
126+
const age = parseInt(req.query.age);
127+
128+
Customer.find({age:age}).select("-__v")
129+
.then(results => {
130+
res.status(200).json({
131+
"message": "Get all Customers with age = " + age,
132+
"size": results.length,
133+
"customers": results
134+
});
135+
}).catch(err => {
136+
console.log(err);
137+
res.status(500).json({
138+
message: "Error!",
139+
error: err
140+
});
141+
});
142+
}
143+
144+
exports.pagination = async (req, res) => {
145+
146+
try {
147+
148+
const page = parseInt(req.query.page);
149+
const limit = parseInt(req.query.limit); // Make sure to parse the limit to number
150+
151+
const offset = page ? page * limit : 0;
152+
153+
// We are using the '3 layer' architecture explored on the 'bulletproof node.js architecture'
154+
// Basically, it's just a class where we have our business logic
155+
156+
let results = await Customer.find({}) // You may want to add a query
157+
.skip(offset) // Always apply 'skip' before 'limit'
158+
.limit(limit)
159+
.select("-__v"); // This is your 'page size'
160+
161+
let numOfCustomer = await Customer.countDocuments({});
162+
163+
res.status(200).json({
164+
"message": "Paginating is completed! Query parameters: page = " + page + ", limit = " + limit,
165+
"totalPages": Math.ceil(numOfCustomer / limit),
166+
"totalItems": numOfCustomer,
167+
"limit": limit,
168+
"currentPageSize": results.length,
169+
"customers": results
170+
});
171+
} catch (error) {
172+
res.status(500).send({
173+
message: "Error -> Can NOT complete a paging request!",
174+
error: error.message,
175+
});
176+
}
177+
178+
}
179+
180+
exports.paginationfilterandsort = async (req, res) => {
181+
try {
182+
const page = parseInt(req.query.page);
183+
const limit = parseInt(req.query.limit); // Make sure to parse the limit to number
184+
const age = parseInt(req.query.age);
185+
186+
const offset = page ? page * limit : 0;
187+
188+
let results = await Customer.find({age: age}) // You may want to add a query
189+
.skip(offset) // Always apply 'skip' before 'limit'
190+
.limit(limit)
191+
.sort({"firstname": 1, "lastname": -1})
192+
.select("-__v"); // This is your 'page size'
193+
194+
let numOfCustomer = await Customer.countDocuments({age: age});
195+
196+
res.status(200).json({
197+
"message": "Paginating is completed! Query parameters: page = " + page + ", limit = " + limit,
198+
"totalPages": Math.ceil(numOfCustomer / limit),
199+
"totalItems": numOfCustomer,
200+
"limit": limit,
201+
"age-filtering": age,
202+
"currentPageSize": results.length,
203+
"customers": results
204+
});
205+
} catch (error) {
206+
res.status(500).send({
207+
message: "Error -> Can NOT complete a paging + filtering + sorting request!",
208+
error: error.message,
209+
});
210+
}
211+
};
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const mongoose = require('mongoose');
2+
3+
const CustomerSchema = mongoose.Schema({
4+
firstname: String,
5+
lastname: String,
6+
address: String,
7+
age: {
8+
type: Number,
9+
min: 18,
10+
max: 65,
11+
required: true
12+
},
13+
copyrightby: {
14+
type: String,
15+
default: 'https://loizenai.com'
16+
}
17+
});
18+
19+
module.exports = mongoose.model('Customer', CustomerSchema);
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
module.exports = function(app) {
2+
3+
var customers = require('../controllers/customer.controller.js');
4+
5+
// Create a new Customer
6+
app.post('/api/customer/create', customers.create);
7+
8+
// Retrieve all Customer
9+
app.get('/api/customer/retrieveinfos', customers.findall);
10+
11+
// Retrieve a single Customer by Id
12+
app.get('/api/customer/findone/:id', customers.findone);
13+
14+
// Update a Customer with Id
15+
app.put('/api/customer/updatebyid/:id', customers.update);
16+
17+
// Delete a Customer with Id
18+
app.delete('/api/customer/deletebyid/:id', customers.delete);
19+
20+
app.get('/api/customer/filteringbyage', customers.filteringByAge);
21+
22+
app.get('/api/customer/pagination', customers.pagination);
23+
24+
app.get('/api/customer/pagefiltersort', customers.paginationfilterandsort);
25+
}

0 commit comments

Comments
 (0)