Node.js and Express.js part 3

ok so lets get started with mongodb, for starters create your new cluster and connect with mongodb compass

npm i mongoose

go to config/config.env and add

MONGO_URI=mongodb://localhost:27017/dev-learn

instead of dev-learn you can add any name as it will automatically create the database, you need to have mongodb installed in you system

now in config folder create a file named db.js

in db.js add

const mongoose = require('mongoose');const connectDB = async () => {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
console.log(`MongoDB Connected: ${conn.connection.host}`);
};

module.exports = connectDB;

this a async await code to connect to database now the main connection function is to be established in server.js so just go to server.js and replace the whole code with

const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const connectDB = require('./config/db');
// Load env vars
dotenv.config({ path: './config/config.env' });
//connect to db
connectDB();
// Route files
const bootcamps = require('./routes/bootcamps');
const app = express();// dev logging middleware
if (process.env.NODE_ENV == 'development') {
app.use(morgan('dev'));
}
// Mount routers
app.use('/api/v1/bootcamps', bootcamps);
const PORT = process.env.PORT || 5000;const server = app.listen(
PORT,
console.log(`server running in ${process.env.NODE_ENV} mode on PORT ${PORT}`)
);
//handle unhandled promise rejection
process.on('unhandledRejection', (err, promise) => {
console.log(`Error: ${err.message}`);
//console.log('dsds');
// Close server & exit process
//server.close(() => process.exit(1));
});

you can see that we have added the connectDB() function and the exception is resolved at last where we have unhandledRejection

now come to root and create folder models and file Bootcamp.js

inside bootcamp.js add

const mongoose = require('mongoose');const BootcampSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, 'Please add a name'],
unique: true,
trim: true,
maxlength: [50, 'Name can not be more than 50 characters']
},
slug: String,
description: {
type: String,
required: [true, 'Please add a description'],
maxlength: [500, 'Description can not be more than 500 characters']
},
website: {
type: String,
match: [
/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/,
'Please use a valid URL with HTTP or HTTPS'
]
},
phone: {
type: String,
maxlength: [20, 'Phone number can not be longer than 20 characters']
},
email: {
type: String,
match: [
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
'Please add a valid email'
]
},
address: {
type: String,
required: [true, 'Please add an address']
},
location: {
// GeoJSON Point
type: {
type: String,
enum: ['Point']
},
coordinates: {
type: [Number],
index: '2dsphere'
},
formattedAddress: String,
street: String,
city: String,
state: String,
zipcode: String,
country: String
},
careers: {
// Array of strings
type: [String],
required: true,
enum: [
'Web Development',
'Mobile Development',
'UI/UX',
'Data Science',
'Business',
'Other'
]
},
averageRating: {
type: Number,
min: [1, 'Rating must be at least 1'],
max: [10, 'Rating must can not be more than 10']
},
averageCost: Number,
photo: {
type: String,
default: 'no-photo.jpg'
},
housing: {
type: Boolean,
default: false
},
jobAssistance: {
type: Boolean,
default: false
},
jobGuarantee: {
type: Boolean,
default: false
},
acceptGi: {
type: Boolean,
default: false
},
createdAt: {
type: Date,
default: Date.now
}
}
);
module.exports = mongoose.model('Bootcamp',BootcampSchema);

as you can guess this is the Schema for bootcamps course

Now in server.js right down to const app = express(); add

app.use(express.json());

and make sure to have headers in postman as key:Content-Type, value:application/json

WORKING WITH CRUD

now in controller/bootcamps.js add this in above

const Bootcamp = require('../models/Bootcamp');

and update this module with given code

exports.createBootcamp = async (req,res,next) => {const bootcamp = await Bootcamp.create(req.body);res.status(201).json({success:true,data:bootcamp});}

now go to postman and set you headers as mentioned above and make post request to api/v1/bootcamps which makes the request to create the bootcamp and in body at raw format send this

{"name": "Devworks xczxcxz","description": "Devworks is a full stack JavaScript Bootcamp located in the heart of Boston that focuses on the technologies you need to get a high paying job as a web developer","website": "https://devworks.com","phone": "(222) 111-1111","email": "enroll@devworks.com","address": "233 Bay State Rd Boston MA 02215","careers": ["Web Development", "UI/UX", "Business"],"housing": true,"jobAssistance": true,"jobGuarantee": false,"acceptGi": true}

if everything goes correct then this json will get added to you mongodb database

now to resolve the errors like in schema we have defined that the duplicate name is not allowed to have this exception in controller just replace the previous code of controllers/bootcamps.js

exports.createBootcamp = async (req,res,next) => {
try{
const bootcamp = await Bootcamp.create(req.body);
res.status(201).json({
success:true,
data:bootcamp
});
} catch (err){
res.status(400).json({sucess:false});
}
}

the catch block will handle the exceptions

go on and change the other to get single and all bootcamps

exports.getBootcamps = async (req,res,next) => {
try {
const bootcamps = await Bootcamp.find();
res.status(200).json({success:true,data:bootcamps});
} catch (err) {
res.status(400).json({sucess:false});
}
}
exports.getBootcamp = async (req,res,next) => {
try {
const bootcamp = await Bootcamp.findById(req.params.id);
if(!bootcamp){
return res.status(400).json({sucess:false});
}
res.status(200).json({success:true,data:bootcamp});
} catch (err) {
res.status(400).json({sucess:false});
}
}

now add the other functionalities to update and delete

exports.updateBootcamp = async (req,res,next) => {
try{
const bootcamp = await Bootcamp.findByIdAndUpdate(req.params.id,req.body,{
new:true,
runValidators:true
});
if(!bootcamp){
return res.status(400).json({sucess:false});
}
res.status(200).json({sucess:true,data:bootcamp});
} catch(err){
res.status(400).json({sucess:false});
}
};
exports.deleteBootcamp = async (req,res,next) => {
try{
const bootcamp = await Bootcamp.findByIdAndDelete(req.params.id);
if(!bootcamp){
return res.status(400).json({sucess:false});
}
res.status(200).json({sucess:true,data:{}});
} catch(err){
res.status(400).json({sucess:false});
}
};

So that’s it we have created a simple CRUD based API of bootcamps

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store