- Initialize a directory
- Start express
- Connect Express to Mongo
- SEED DB
- Create INDEX
- Create CREATE Route
- Create Fruits Model
- Have Create Route Create data in MongoDB
- INDEX Route
- SHOW Route
- DELETE Route
- UPDATE Route
mkdir express-mongoose-crud-app
npm init
npm install express
touch server.js
- Edit package.json to have
"main": "server.js",
In server.js
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('listening');
});
Let's build a POST route first. In server.js
add this:
app.post('/fruits', (req, res)=>{
res.send('received');
});
Test the route in Postman. Note - you do not have to enter any for data for this test.
Next, we'll need to add some Express middleware to properly translate JSON data. Middleware is any code that we want to run between receiving the request and passing it along to the route. Typically, middleware is a .use
method.
Body Parser is an npm package that creates a req.boody
object. It is now included in Express by default.
app.use(express.json());
Check to see if req.body
works, update the route to respond with the body of the form.
app.post('/fruits', (req, res)=>{
res.json(req.body);
});
In Postman, make sure that the Body is raw
JSON.
Let's add some conditional logic based on whether a fruit is ripe and readyToEat
. This will imitate a checkbox in a form:
app.post('/fruits', (req, res)=>{
if(req.body.readyToEat === 'on'){ //if checked, req.body.readyToEat is set to 'on'
req.body.readyToEat = true;
} else { //if not checked, req.body.readyToEat is undefined
req.body.readyToEat = false;
}
res.json(req.body);
});
npm install mongoose
- Inside
server.js
:
const mongoose = require('mongoose');
//... and then farther down the file
mongoose.connect('mongodb://localhost:27017/basiccrud', { useNewUrlParser: true});
mongoose.connection.once('open', ()=> {
console.log('connected to mongo');
});
Our server.js so far
const express = require('express');
const app = express();
const mongoose = require('mongoose');
app.use(express.urlencoded({ extended: true }));
mongoose.connect('mongodb://localhost:27017/basiccrud', { useNewUrlParser: true });
mongoose.connection.once('open', () => {
console.log('connected to mongo');
});
app.post('/fruits', (req, res) => {
if (req.body.readyToEat === 'on') { //if checked, req.body.readyToEat is set to 'on'
req.body.readyToEat = true;
} else { //if not checked, req.body.readyToEat is undefined
req.body.readyToEat = false;
}
res.json(req.body);
});
app.listen(3000, () => {
console.log('listening');
});
-
mkdir models
-
touch models/fruit.js
-
Create the fruit schema
const mongoose = require('mongoose'); const fruitSchema = new mongoose.Schema({ name: { type: String, required: true }, color: { type: String, required: true }, readyToEat: Boolean }); const Fruit = mongoose.model('Fruit', fruitSchema); module.exports = Fruit;
-
Import
Fruit
intoserver.js
const mongoose = require('mongoose'); const Fruit = require('./models/fruit');
Sometimes you might need to add data to your database for testing purposes. You can do so like this via a route:
// FRUITS SEED ROUTE
app.get('/fruits/seed', (req, res) => {
Fruit.insertMany([
{
name: 'grapefruit',
color: 'pink',
readyToEat: true
},
{
name: 'grape',
color: 'purple',
readyToEat: false
},
{
name: 'avocado',
color: 'green',
readyToEat: true
}
], (err, fruits) => {
res.json(fruits);
})
});
Inside server.js
.
app.post('/fruits', (req, res)=>{
if(req.body.readyToEat === 'on'){ //if checked, req.body.readyToEat is set to 'on'
req.body.readyToEat = true;
} else { //if not checked, req.body.readyToEat is undefined
req.body.readyToEat = false;
}
Fruit.create(req.body, (error, createdFruit)=>{
res.json(createdFruit);
});
});
app.get('/fruits', (req, res) => {
Fruit.find({}, (err, allFruits) => {
if (err) { console.log(err) }
res.json(allFruits);
});
});
app.get('/fruits/:id', (req, res)=>{
Fruit.findById(req.params.id, (err, foundFruit)=>{
if (err) { res.send(err) }
res.json(foundFruit);
});
});
app.delete('/fruits/:id', (req, res)=>{
Fruit.findByIdAndRemove(req.params.id, (err, deletedFruit)=>{
if (err) { console.log(err) }
res.json(deletedFruit);
});
});
app.put('/fruits/:id', (req, res)=>{
if(req.body.readyToEat === 'on'){
req.body.readyToEat = true;
} else {
req.body.readyToEat = false;
}
Fruit.findByIdAndUpdate(req.params.id, req.body, {new:true}, (err, updatedModel)=>{
res.send(updatedModel);
});
});