Express & MongoDB and how to connect to React
- Packages to be installed include
express
,mongodb
,mongoose
&body-parser
(Concurrently & Nodemon optional but it will be helpful) - Initialise a Server.js file
- Import the necessary packages
const express = require('express');
const mongoose = require('mongoose');
const { MongoClient, ServerApiVersion } = require('mongodb');
const bodyParser = require('body-parser');
const app = express()
- Connection to MongoDB Cloud
const URI = "mongodb+srv://<username>:<password>@cluster0.gcqsxcl.mongodb.net/
myApp?retry=true";
//Use a dotenv file to store sensitive info such as the above URL
//showing here just for example
const PORT = process.env.PORT || 3001;
mongoose.connect(URL);
app.use(bodyParser.json());
- Create a Schema and Model(Mongoose)
// SCHEMA //
const carSchema = mongoose.Schema({
brand: String,
model: String,
year: Number,
avail: Boolean
});
// MODEL //
const Car = mongoose.model('Car', carSchema);
CRUD Operations
There are various ways to perform CRUD operations, this way is just one of them and it's best to always refer to the documentation for the most up to date method!
- CreateCar (
CREATE
)
//App.js (Frontend)
const onCarSubmit = () => {
axios.post('/api/cars', {
brand: 'Tesla',
model: 'Model 3',
year: 2000,
avail: true
})
.then(res => {
console.log(response.data);
getCars();
})
}
//Server.js (Backend)
app.post('/api/cars', (req,res) => {
const addCar = new Car({
brand: req.body.brand,
model: req.body.model,
year: req.body.year,
avail: req.body.avail
});
addCar.save((err, result) => {
if (err) {
throw err;
}
res.json(doc);
});
})
- GetCars (
READ
)
//App.js (Frontend)
const getCars = () => {
axios.get('/api/getCars')
.then(response => {
console.log(response.data);
});
}
//Server.js (Backend)
app.get('/api/getCars', (req,res) => {
Car.find({}, (err,result) => {
if (err) {
throw err;
}
res.json(result);
});
})
- updateCar (
UPDATE
)
//App.js (Frontend)
const onCarUpdate = () => {
axios.post('/api/updatecar', {
_id: '6370a55287a49bb363fb487a',
brand: 'Tesla'
})
.then(response => {
console.log(response.data);
getCars();
});
}
//Server.js (Backend)
app.post('/api/updatecar', (req,res) => {
const _id = req.body._id;
const brand = req.body.brand;
Car.findByIdAndUpdate(_id, {$set: {brand:brand}}, (err,result) => {
if (err) {
throw err;
}
res.json(result);
});
})
- deleteCar (
DELETE
)
//App.js (Frontend)
const onCarRemove = () => {
axios.post('/api/removecar', {
_id: '637a55287a49bb363fb487a'
})
.then(response => {
console.log(response.data);
getCars();
});
}
//Server.js (Backend)
app.post('/api/removecar', (req,res) => {
const _id = req.body._id;
Car.findByIdAndRemove({_id}, (err,result) => {
if (err) {
throw err;
}
res.json(result);
});
})