Code Monkey home page Code Monkey logo

lesson-w10d03-crud-mongoose-express's Introduction

CRUD Express App with Mongoose

Lesson Objectives

  1. Initialize a directory
  2. Start express
  3. Connect Express to Mongo
  4. SEED DB
  5. Create INDEX
  6. Create CREATE Route
  7. Create Fruits Model
  8. Have Create Route Create data in MongoDB
  9. INDEX Route
  10. SHOW Route
  11. DELETE Route
  12. UPDATE Route

Initialize a directory

  1. mkdir express-mongoose-crud-app
  2. npm init
  3. npm install express
  4. touch server.js
  5. Edit package.json to have "main": "server.js",

Build express app

In server.js

const express = require('express');
const app = express();

app.listen(3000, () => {
    console.log('listening');
});

Test Fruit Route and req.body

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.

Test JSON request data with Postman

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);
});


Connect Express to Mongo

  1. npm install mongoose
  2. 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');
});

Create Fruits Model

  1. mkdir models

  2. touch models/fruit.js

  3. 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;
  4. Import Fruit into server.js

    const mongoose = require('mongoose');
    const Fruit = require('./models/fruit');

Create a Seed Route

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);
  })
});


Use Mongoose to persist Data in MongoDB

Inside server.js.

CREATE Route

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);
    });
});

INDEX Route

app.get('/fruits', (req, res) => {
  Fruit.find({}, (err, allFruits) => {
    if (err) { console.log(err) }
    res.json(allFruits);
  });
});

SHOW Route

app.get('/fruits/:id', (req, res)=>{
  Fruit.findById(req.params.id, (err, foundFruit)=>{
    if (err)  { res.send(err) }
    res.json(foundFruit);
  });
});

DELETE Route

app.delete('/fruits/:id', (req, res)=>{
  Fruit.findByIdAndRemove(req.params.id, (err, deletedFruit)=>{
	 if (err)  { console.log(err) }
    res.json(deletedFruit);
  });
});

UPDATE Route

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);
    });
});


Additional Resources

lesson-w10d03-crud-mongoose-express's People

Contributors

marcwright avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.