Basic express CRUD with MongoDB

Background

This is a basic overview of how to do a CRUD process in expressJS with MongoDB.

Database.

SQL database stores related data tables. NOSQL database stores json like field-value pairs. You can still have primary keys, index, and relationships. I wont talk too much about them here. I’ll do another post when I’m more familar with NOSQL and MYSQL. I’ll be using mongodb for our database. MongoDB is one of the popular NOSQL databases. MongoDB is a document database in which one collection holds different documents. Number of fields, content and size of the document can differ from one document to another.

I’ll be using mongoose which is a ORM for mongodb. Mongoose provides easier API for dealing with Mongodb.

Framework

ExpressJS is the most popular nodeJS framework. Many other frameworks are bult upon express. Hence, expressJS is the backbone a lot of backend frameworks. Express is very very light and minimalistic, so there’s a lot of work that the developer need to do. That’s also good because I have more control and I can really learn from it.

**Sidenote: I was playing around with Rails before the thing about rails is that it does a lot of things for you. A lot of things just happens and it’s hard to know why. It’s like magic. Express doesn’t do that much so I can really understand how things work.

Instructions

I’ll be referring to my express blog project. You can download it or just refer it on my github.

  1. Install mongoose in package json

    1
    npm install mongoose
  2. Setup connection in app.js

    1
    2
    3
    4
    5
    6
    // app.js
    const mongoose = require('mongoose')

    ...
    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost/blogv2')
  3. Creat model/post.js with schema

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // models/post.js
    let mongoose = require('mongoose')

    // Post Schema
    let postSchema = mongoose.Schema({
    title: { type: String, required: true },
    body: { type: String, required: true }
    })

    let Post = module.exports = mongoose.model('Post', postSchema)
  4. Go into to mongo shell and enter some sample data

    1
    db.articles.insert({title: "Article one", body: "this is article one"})
  5. routes/posts.js create CRUD routes

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    var express = require('express');
    var router = express.Router();


    // Bring in Models
    let Post = require('../models/post')

    /* GET Posts . */
    router.get('/', function(req, res, next) {
    Post.find({}, function(err, posts){
    if (err) {
    console.log(err)
    } else {
    res.render('posts/index', { posts: [...posts] });
    }
    })
    });

    // GET Add Post Route
    router.get('/add', function(req, res){
    res.render('posts/addPost')
    })

    // POST Add Post Route
    router.post('/add', function(req, res){
    var post = new Post({
    title: req.body.title,
    body: req.body.body
    });
    post.save(function(err, resp) {
    if (err) {
    console.log(err);
    res.send({
    message: 'something went wrong'
    });
    } else {
    res.redirect('/posts')
    }
    });
    })

    // Get Show Post"/posts/<%= post._id%>"
    router.get('/:id', function(req,res){
    Post.findById(req.params.id, function(err, post){
    res.render('posts/showPost',{
    post: post,
    })
    })
    })

    // Get Edit Form
    router.get('/edit/:id', function(req,res){
    Post.findById(req.params.id, function(err, post){
    res.render('posts/editPost',{
    post: post
    })
    })
    })

    //Post Edit Route
    router.post('/edit/:id', function(req, res){
    let post = {}
    post.title = req.body.title
    post.body = req.body.body

    let query = { _id: req.params.id }
    Post.update(query, post, function(err){
    if(err){
    console.log(err)
    return
    } else {
    res.redirect('/posts')
    }
    })
    })

    // DELETE Route
    router.delete('/delete/:id', function(req, res){
    let query = { _id: req.params.id}
    Post.remove(query, function(err){
    if(err){
    console.log()
    }
    res.send('Success')
    })
    })
  6. Generate the index views to see if all posts shows up

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

    <%- include ../partials/header %>

    <a href="/posts/add" class="btn btn-md btn-primary">Add post</a>
    <h1>Posts Index Pages</h1>
    <h3>Here are the Following posts</h3>
    <% posts.forEach(function(post){ %>
    <h2><%= post.title %></h2>
    <p><%= post.body %></p>
    <a href="/posts/<%= post._id%>">Show</a>
    <a href="/posts/edit/<%= post._id%>">Edit</a>
    <a href="#" class="deletePost" data-id="<%= post._id%>">Delete</a>
    <% }) %>

    <%- include ../partials/footer %>
  7. Generate ADD/Update views

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22

    <%- include ../partials/header %>

    <a href="/posts" class="btn btn-lg btn-default">Back To Index</a>
    <h1>Add Post</h1>

    <form method='POST', action='/posts/add'>
    <div id="form-group">
    <label>Title</label>
    <input name='title' type="text" class="form-control">
    </div>
    <div id="form-group">
    <label>Body</label>
    <input name='body' type="text" class="form-control">
    </div>
    <br>
    <input value='Submit' type="Submit" class="btn btn-primary">

    </form>


    <%- include ../partials/footer %>
  8. Setup the DELETE link. In out public/js folder, create a main.js file.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    $(document).ready(function(){
    $('.deletePost').on('click', deletePost);
    });

    function deletePost(){
    var confirmation = confirm('Are you sure?')

    if(confirmation){
    $.ajax({
    type: 'DELETE',
    url: '/posts/delete/' + $(this).data('id')
    }).done(function(response){
    window.location.replace('/posts')
    })
    window.location.replace('/posts')

    } else {
    return false;
    }
    }

Here’s the overview of how to create CRUD. You may need to refer to my github project for more details.