Node.js and Express.js part 3

npm i mongoose
MONGO_URI=mongodb://localhost:27017/dev-learn
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;
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));
});
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);
app.use(express.json());

WORKING WITH CRUD

now in controller/bootcamps.js add this in above

const Bootcamp = require('../models/Bootcamp');
exports.createBootcamp = async (req,res,next) => {const bootcamp = await Bootcamp.create(req.body);res.status(201).json({success:true,data:bootcamp});}
{"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}
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});
}
}
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});
}
}
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});
}
};

--

--

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