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.
Install mongoose in package json
1npm install mongooseSetup connection in app.js
123456// app.jsconst mongoose = require('mongoose')...mongoose.Promise = global.Promise;mongoose.connect('mongodb://localhost/blogv2')Creat model/post.js with schema
12345678910// models/post.jslet mongoose = require('mongoose')// Post Schemalet postSchema = mongoose.Schema({title: { type: String, required: true },body: { type: String, required: true }})let Post = module.exports = mongoose.model('Post', postSchema)Go into to mongo shell and enter some sample data
1db.articles.insert({title: "Article one", body: "this is article one"})routes/posts.js create CRUD routes
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586var express = require('express');var router = express.Router();// Bring in Modelslet 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 Routerouter.get('/add', function(req, res){res.render('posts/addPost')})// POST Add Post Routerouter.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 Formrouter.get('/edit/:id', function(req,res){Post.findById(req.params.id, function(err, post){res.render('posts/editPost',{post: post})})})//Post Edit Routerouter.post('/edit/:id', function(req, res){let post = {}post.title = req.body.titlepost.body = req.body.bodylet query = { _id: req.params.id }Post.update(query, post, function(err){if(err){console.log(err)return} else {res.redirect('/posts')}})})// DELETE Routerouter.delete('/delete/:id', function(req, res){let query = { _id: req.params.id}Post.remove(query, function(err){if(err){console.log()}res.send('Success')})})Generate the index views to see if all posts shows up
123456789101112131415<%- 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 %>Generate ADD/Update views
12345678910111213141516171819202122<%- 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 %>Setup the DELETE link. In out public/js folder, create a main.js file.
1234567891011121314151617181920$(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.