Node.js Express Image Gallery Using MongoDB & Mongoose Library Full Project

Node.js Express Image Gallery Using MongoDB & Mongoose Library Full Project

Welcome folks today in this blog post we will talk about how to make a image gallery in node.js express with the help of mongodb database and the mongoose library to connect to the mongodb database.The step by step youtube video is shown below just watch the video to follow with the blog. All the source code is given below copy and paste the code.

 

 

Requirements

 

npm i express

 

Express will be the server on which the app will run on Port 5000

 

npm i multer

 

Multer will be the library used for uploading the images on the server

 

npm i express-handlebars

 

Express handlebars will be the template engine on which the app will run.

 

npm i mongoose

 

Mongoose will be the library to connect with the database that will be used for the application

 

npm i --save-dev nodemon

 

Nodemon will be a dev dependency which will automatically restart the application when we make any kinds of changes in the application.

 

 

 

Now Make a App.js file that will be the starting point of the application

 

 

const express = require("express");

const app = express();

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

    res.send("hello world")
});

app.listen(5000, () => {
  console.log("App is listening on Port 5000");
});

 

So in this block of code we are initializing a express application and then starting a new app. When someone goes to the home route then we return hello world as a response. We start the application using the listen method at port 5000

See also  Build a Stripe.js Payment Gateway Invoice Billing PDF Document Generator in Javascript Using stripe-pdf-invoice Library in Browser Full Project For Beginners

 

Initializing the HandleBars Template Engine in App

 

In order to use handlebars into your application you first of all need to create a directory structure such as first of all you need to create views directory in that directory you need to create layout directory like this

 

 

main.handlebars file

 

<!DOCTYPE html>
<html>

<head>
  <title>Image Gallery in Node.js Express Using Multer and MongoDB</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
</head>

<body>
  {{{body}}}
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

</html>

 

home.handlebars

 

<div class="container">
    <br>
    <h1 class="text-center">
        Image Gallery
    </h1>
    <br>
    <form action="/" method="POST" enctype="multipart/form-data">

        <div class="form-group">
            <label for="Select Image:">Select Image:</label>
            <input type="file" name="image" class="form-control" id="">
        </div>
        <br>
        <div class="form-group">
            <button class="btn btn-block btn-danger">
                Upload Image
            </button>
        </div>
    </form>
</div>

 

Now Modify App.js to include the handlebars

 

const express = require("express");

var exphbs = require("express-handlebars");


const app = express();

app.engine("handlebars", exphbs());
app.set("view engine", "handlebars");


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

    res.render("home")
});


app.listen(5000, () => {
  console.log("App is listening on Port 5000");
});

 

Now if you execute the app on command prompt you will see the following output

 

 

 

 

Multer Image Upload

 

Now in this section we will be uploading image files using multer so first of all you need to create the public directory inside the root project and inside it you need to create a directory named images to hold the uploaded images such as

 

 

app.use(express.static("public/images"));

 

const multer = require("multer");

var Storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, "./public/images");
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
  },
});

var upload = multer({
  storage: Storage,
}).single("image"); //Field name and max count

 

See also  Build a Physics Electricity Energy and Power Calculator in Browser Using Javascript Full Project For Beginners

 

app.post("/", (req, res) => {
  upload(req, res, function (err) {
    if (err) {
      console.log(err);
      return res.end("Something went wrong");
    } else {
      console.log(req.file.path);
      var imageName = req.file.filename;


            res.render('home',success:true})
 
     
    }
  });
});

 

In this section of code we have successfully completed the operation of uploading images to the images folder

 

{{#if success}}
        <div class="alert alert-success alert-dismissible">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
            <strong>Success!</strong> Your Image File is Uploaded.
        </div>
        {{/if}}

 

Handlebars code to show success message when image is uploaded

 

const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost:27017/imagesDB',{useNewUrlParser:true,useUnifiedTopology:true})

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("h");
});

var uploadSchema = new mongoose.Schema({
    imagename:String
})

var uploadModel = mongoose.model('image',uploadSchema)

module.exports = uploadModel

 

In this section of code we are connecting to mongodb and describing the schema of image file and exporting it.

 

Full Source Code

 

const express = require("express");

var exphbs = require("express-handlebars");

const multer = require("multer");

const imageModel = require("./models/upload");

const imageData = imageModel.find({})

const app = express();

app.engine("handlebars", exphbs());
app.set("view engine", "handlebars");

app.use(express.static("public/images"));

var Storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, "./public/images");
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
  },
});

var upload = multer({
  storage: Storage,
}).single("image"); //Field name and max count

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

    imageData.exec(function(err,data){
        if(err) throw err;

        console.log(data)

        res.render('home',{records:data})
    })
});

app.post("/", (req, res) => {
  upload(req, res, function (err) {
    if (err) {
      console.log(err);
      return res.end("Something went wrong");
    } else {
      console.log(req.file.path);
      var imageName = req.file.filename;

      var imageDetails = new imageModel({
        imagename: imageName,
      });

      imageDetails.save(function (err, doc) {
        if (err) throw err;

        console.log("Image Saved");

        imageData.exec(function(err,data){
            if(err) throw err;


            res.render('home',{records:data,success:true})
        })
      });
    }
  });
});

app.listen(5000, () => {
  console.log("App is listening on Port 5000");
});

 

See also  jsPDF Tutorial to Fully Fit or Stretch Canvas in PDF Document Using Javascript Full Tutorial For Beginners

 

DOWNLOAD SOURCE CODE

 

Leave a Reply