nodejs – use mongodb for CRUD application

In this article I’m going to create a minimalistic CRUD application with nodejs, express and mongodb. First I will show you the pug files and finally the nodejs code for creating our application.

To use mongodb you have to install it on your (ubuntu) box with:

sudo apt install mongodb

Then we have to add the node module to our project (and package.json) with:

npm install mongodb --save

Now on to the pug files. First of all the ‘index.pug’ file (remember pug files are stored in the views folder (default).

html
  head
  body
    h2 Add email address
    a(href='/all') All
    form(method='POST' action='/add')
      div
        p Your email address
        input#name.form-control(type='text', placeholder='Email address' required name='email')
      p 
          button.btn.btn-primary(type='submit') Sign up

Then we have the ‘all.pug’ file which gives us an overview of entries in the database together with a link to delete or edit the entry

html
  head
  body
    h2 List of email addresses
    a(href='/') Add
    table
        each email in email_addresses
            tr#email_list_item    
                td #{email.email}
                td #{email.i}
                td
                    a(href='delete?id=' + email._id) x
                td
                    a(href='edit?id=' + email._id) e

We have an ‘edit.pug’ file to edit our document entries

html
  head
  body
    h2 Update email address
    a(href='/all') All
    form(method='POST' action='/edit')
        input#email.form-control(type='hidden', name='id' value=id)
        div
            p Edit email address
            input#email.form-control(type='text', placeholder='Email address' required name='email' value=email_address)
        p 
            button.btn.btn-primary(type='submit') Update
        p

And finally we have our app.js nodejs application.

const express = require('express')
const app = express()
const port = 3000

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.set('view engine', 'pug')

var ObjectId = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/", { useNewUrlParser: true }, function(err, client) {

    if (err) throw (err)
    mongoDB = client.db('emailaddresses')
    app.listen(port, () => console.log(`Listening on port ${port}`))

});

app.get('/', (req, res) =>  {

        res.render('index')

    }
)

app.post('/add', (req, res) =>  {
    
    mongoDB.collection('email_addresses').insertOne(req.body, (err, result) => {

        if (err) throw err
        res.redirect('all')

    })
})

app.get('/all', (req, res) =>  {

    mongoDB.collection('email_addresses').find().toArray((err, results) => {

        if (err) throw err
        res.render('all', { 'email_addresses': results })

    })

})

app.get('/delete', (req, res) =>  {

    mongoDB.collection('email_addresses').deleteOne({'_id': ObjectId(req.query.id)}, (err, results) => {

        if (err) throw err
        res.redirect('/all')
        
    });
})

app.get('/edit', (req, res) =>  {

    mongoDB.collection('email_addresses').findOne({'_id': ObjectId(req.query.id)}, (err, result) => {

        if (err) throw err
        res.render('edit', { 'email_address' : result.email, 'id' : result._id })

    });
})

app.post('/edit', (req, res) => {

    mongoDB.collection('email_addresses').updateOne({'_id': ObjectId(req.body.id)}, { $set:req.body }, (err, result) => {

        if(err) throw err
        res.redirect('/all')

    });
})
Share

Leave a Reply

Your email address will not be published.