Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Basic Simple CRUD Application with Express and MongoDB

In this post i have created a basic simple application using Express and MongoDB to Create, Read, Update and Delete data in MongoDB.

Crud-express-mongodb


To use this application you need to install Node.js and also have some basic knowledge of typing commands.

To check if you have Node installed, open up your command line and run the following code:
node -v

In this example we are going to store databases on cloud like mlab.com. So you need to create your database before starting this. 

Now let's create required files step by step:

Step1: Create server.js file and add following code

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;

/////Body parser
app.use(bodyParser.urlencoded({extended: true}))
//app.use(bodyParser.json());
app.use(express.static('public'));
app.set('view engine', 'ejs')


/////MongoDB
var db;
var ObjectId = require('mongodb').ObjectID;

MongoClient.connect('your_mongodb_url', (err, database) => {
    if (err) {
        throw err;
    }

    db = database.db('db_name')
    db.collection('customer')
    app.listen(3000, () => {
        console.log('database connected listening on 3000');
    })
})

app.get('/', (req, res) => {
    db.collection('customer').find().toArray((err, result) => {
        if (err) {
            throw err;
        }
        res.render('index.ejs', {data: result})
    })
})

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

    var myobj = {name: req.body.name, address: req.body.address};
    db.collection("customer").insertOne(myobj, function (err, result) {
        if (err) {
            throw err;
        }
        console.log("1 record inserted");
        res.redirect('/')
    });
})


////////////////////Update
app.get('/update/:id', (req, res) => {
    var user_id = req.params.id;
    console.log(user_id);
    var query = {_id: ObjectId(user_id)};
    db.collection("customer").find(query).toArray(function (err, result) {
        if (err) {
            throw err;
        }
        console.log(result);
        res.render('update.ejs', {data: result})
    });
})

app.post('/updatepost', (req, res) => {
    var myquery = {_id: ObjectId(req.body.id)};
    //var newvalues = {name: req.body.name, address: req.body.quote};
    var newvalues = {$set: {name: req.body.name, address: req.body.address}};
    var extra = {upsert: true};
    db.collection("customer").updateOne(myquery, newvalues, extra, function (err, result) {
        if (err) {
            throw err;
        }
        console.log("1 record updated");
        res.redirect('/')
    });
})


/////////////////Delete
app.get('/delete/:id', (req, res) => {
    var user_id = req.params.id;
    console.log(user_id);
    var query = {_id: ObjectId(user_id)};
    db.collection("customer").deleteOne(query, function (err, obj) {
        if (err) {
            throw err;
        }
        console.log("1 record deleted");
        res.redirect('/')
    });
})

Note: Replace 'your_mongodb_url' with your mongodb url and 'db_name' with the database name.

Step2: Create package.json file and add following code

{
  "name": "node",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js",
    "dev": "nodemon server.js"
  },
  "author": "Hardik Patel",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "ejs": "^2.5.7",
    "express": "^4.16.2",
    "mongodb": "^3.0.1"
  },
  "devDependencies": {
    "nodemon": "^1.14.7"
  }
}

Step3: Create new folder 'views'

Step4: In views folder create new file index.ejs and add following code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Basic CRUD Example</title>
</head>
<body>
  <ul class="quotes">
  <% for(var i=0; i<data.length; i++) {%>
    <li class="quote">
      <span><%= data[i].name %>: </span>
      <span><%= data[i].address %></span>
      <!--<span><%= data[i]._id %></span>-->
      <a href="update/<%= data[i]._id %>">Update</a>
      <a href="delete/<%= data[i]._id %>">Delete</a>
    </li>
  <% } %>
  </ul>

  <form action="/addnew" method="POST">
    <input type="text" placeholder="name" name="name">
    <input type="text" placeholder="address" name="address">
    <button type="submit">Submit</button>
  </form>
</body>
</html>

Step5: In views folder create new file update.ejs and add following code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Basic CRUD Example</title>
</head>
<body>
  <form action="/updatepost" method="POST">
    <input style="width:300px;" type="text" placeholder="name" name="name" value="<%= data[0].name %>">
    <br><br>
    <input style="width:300px;" type="text" placeholder="address" name="address" value="<%= data[0].address %>">
    <br><br>
    <input style="width:300px;" type="text" placeholder="id" name="id" value="<%= data[0]._id %>">
    <br><br>
    <a href="/">Back</a>
    <button type="submit">Update</button>

  </form>
</body>
</html>

Note: Make sure you have added all required node module in your application. You can download required module from here.


Download

Please support us, Like us on Facebook.

 

Copyright @ 2017 HKBlog.