Skip to content

Commit af30b00

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

File tree

7 files changed

+1109
-0
lines changed

7 files changed

+1109
-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: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
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+
customers: [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+
customers: [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')
106+
.then(customer => {
107+
if(!customer) {
108+
return res.status(404).json({
109+
message: "Does Not exist a Customer with id = " + customerId,
110+
error: "404",
111+
});
112+
113+
}
114+
res.status(200).json({
115+
message: "Delete Successfully a Customer with id = " + customerId,
116+
customers: [customer],
117+
});
118+
}).catch(err => {
119+
return res.status(500).send({
120+
message: "Error -> Can NOT delete a customer with id = " + customerId,
121+
error: err.message
122+
});
123+
});
124+
};
125+
126+
exports.filteringByAge = (req, res) => {
127+
const age = parseInt(req.query.age);
128+
129+
Customer.find({age:age}).select("-__v")
130+
.then(results => {
131+
res.status(200).json({
132+
"message": "Get all Customers with age = " + age,
133+
"size": results.length,
134+
"customers": results
135+
});
136+
}).catch(err => {
137+
console.log(err);
138+
res.status(500).json({
139+
message: "Error!",
140+
error: err
141+
});
142+
});
143+
}
144+
145+
exports.pagination = async (req, res) => {
146+
147+
try {
148+
149+
const page = parseInt(req.query.page);
150+
const limit = parseInt(req.query.limit); // Make sure to parse the limit to number
151+
152+
const offset = page ? page * limit : 0;
153+
154+
// We are using the '3 layer' architecture explored on the 'bulletproof node.js architecture'
155+
// Basically, it's just a class where we have our business logic
156+
157+
let results = await Customer.find({}) // You may want to add a query
158+
.skip(offset) // Always apply 'skip' before 'limit'
159+
.limit(limit)
160+
.select("-__v"); // This is your 'page size'
161+
162+
let numOfCustomer = await Customer.countDocuments({});
163+
164+
res.status(200).json({
165+
"message": "Paginating is completed! Query parameters: page = " + page + ", limit = " + limit,
166+
"totalPages": Math.ceil(numOfCustomer / limit),
167+
"totalItems": numOfCustomer,
168+
"limit": limit,
169+
"currentPageSize": results.length,
170+
"customers": results
171+
});
172+
} catch (error) {
173+
res.status(500).send({
174+
message: "Error -> Can NOT complete a paging request!",
175+
error: error.message,
176+
});
177+
}
178+
179+
}
180+
181+
exports.paginationfilterandsort = async (req, res) => {
182+
try {
183+
const page = parseInt(req.query.page);
184+
const limit = parseInt(req.query.limit); // Make sure to parse the limit to number
185+
const age = parseInt(req.query.age);
186+
187+
const offset = page ? page * limit : 0;
188+
189+
let results = await Customer.find({age: age}) // You may want to add a query
190+
.skip(offset) // Always apply 'skip' before 'limit'
191+
.limit(limit)
192+
.sort({"firstname": 1, "lastname": -1})
193+
.select("-__v"); // This is your 'page size'
194+
195+
let numOfCustomer = await Customer.countDocuments({age: age});
196+
197+
res.status(200).json({
198+
"message": "Paginating is completed! Query parameters: page = " + page + ", limit = " + limit,
199+
"totalPages": Math.ceil(numOfCustomer / limit),
200+
"totalItems": numOfCustomer,
201+
"limit": limit,
202+
"age-filtering": age,
203+
"currentPageSize": results.length,
204+
"customers": results
205+
});
206+
} catch (error) {
207+
res.status(500).send({
208+
message: "Error -> Can NOT complete a paging + filtering + sorting request!",
209+
error: error.message,
210+
});
211+
}
212+
};
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
CustomerSchema.virtual('id').get(function(){
20+
return this._id.toHexString();
21+
});
22+
23+
// Ensure virtual fields are serialised.
24+
CustomerSchema.set('toJSON', {
25+
virtuals: true
26+
});
27+
28+
module.exports = mongoose.model('Customer', CustomerSchema);
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
module.exports = function(app) {
2+
3+
var customers = require('../controllers/customer.controller.js');
4+
5+
// Create a new Customer
6+
app.post('/api/customers/create', customers.create);
7+
8+
// Retrieve all Customer
9+
app.get('/api/customers/retrieveinfos', customers.findall);
10+
11+
// Update a Customer with Id
12+
app.put('/api/customers/updatebyid/:id', customers.update);
13+
14+
// Delete a Customer with Id
15+
app.delete('/api/customers/deletebyid/:id', customers.delete);
16+
}

0 commit comments

Comments
 (0)