How to Upload File to Mongodb Compass

Upload and Retrieve Image on MongoDB using Mongoose

Prerequisites: For getting started with this you should have some familiarity with NodeJS, ExpressJS, MongoDB and Mongoose.

  • NodeJS : Information technology is a costless open source server environs that uses JavaScript on the server and runs on various platform (Windows, Linux, Unix, Mac OS X, etc.).Information technology uses asynchronous programming.
  • ExpressJS : It is a NodeJS web application server framework, designed for edifice single-page, multi-page, and hybrid web applications. It is the de facto standard server framework for node.
  • MongoDB : MongoDB is a NoSQL database.MongoDB is a JSON certificate datastore. Information technology allows you lot to shop and query JSON way documents with a few smarts on top.
  • Mongoose : Mongoose is an Object Information Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to interpret between objects in code and the representation of those objects in MongoDB.

To offset, install the required packages and modules:

  • ExpressJS allows u.s.a. to set up middleware to answer to HTTP Requests.
npm install express --save
  • The module "body-parser" enables reading (parsing) HTTP-Postal service data.
npm install body-parser --salvage
  • Mongoose is a MongoDB client library providing object-modelling for apply in an asynchronous environment. Mongoose supports both promises and callbacks.
npm install mongoose --salvage
  • Multer is nodejs middleware used for uploading files.
npm install multer --save
  • Dotenv is a aught-dependency module that loads environment variables from a .env file into process.env.
npm install dotenv --save
  • EJS (Embedded Javascript) is a templating engine for nodejs. This engine helps to create an HTML pages via templates with minimal code.
npm install ejs --save
  • nodemon is a developer tool that automatically restarts the node awarding when file changes in the code directory are detected.  It improves the developer experience when working on node-based applications.  Since this is a development tool and not office of our application code, nosotros use `–save-dev` when installing this module:
npm install nodemon --relieve-dev

Now let'southward commencement coding!  To upload an image and retrieve epitome past MongoDB using Mangoose, follow each of the steps below i by i.

  • Pace 0: Create the file ` .env ` that will contain environment-specific settings.

Javascript

MONGO_URL=mongodb:

PORT=3000

  • Stride ane: Create our server file ` app.js `.  Add together the following code to information technology:

Javascript

var limited = require( 'express' )

var app = express()

var bodyParser = crave( 'body-parser' );

var mongoose = require( 'mongoose' )

var fs = require( 'fs' );

var path = require( 'path' );

require( 'dotenv/config' );

  • Step two: Connect to MongoDB using the URL for your database. Here 'process.env.MONGO_URL' is used for the database URL.  This value is retrieved from ` .env ` as an environs variable by the module `dotenv`.  Add the post-obit code to ` app.js `

Javascript

mongoose.connect(procedure.env.MONGO_URL,

{ useNewUrlParser: true , useUnifiedTopology: true }, err => {

panel.log( 'connected' )

});

  • Stride 3: Once we have established a connection to our database and required all the necessary packages, nosotros can now brainstorm defining our server-side logic. So for storing an image in MongoDB, we need to create a schema with mongoose. For that create the file ` model.js ` file and ascertain the schema. The important point here is that our data type for the epitome is a Buffer which allows united states of america to store our image as data in the class of arrays.

Javascript

var mongoose = require( 'mongoose' );

var imageSchema = new mongoose.Schema({

name: String,

desc: String,

img:

{

data: Buffer,

contentType: String

}

});

module.exports = new mongoose.model( 'Epitome' , imageSchema);

  • Stride 4: We want to set EJS every bit our templating engine with Express. EJS is specifically designed for building unmarried-page, multi-page, and hybrid web applications. Information technology has become the standard server framework for nodejs. The default behavior of EJS is that it looks into the ` views ` binder for the templates to render. Nosotros will create our templates in a later step.
    Add together the following code to ` app.js `:

Javascript

app.utilise(bodyParser.urlencoded({ extended: faux }))

app.use(bodyParser.json())

app.fix( "view engine" , "ejs" );

  • Step v: We will define the storage path for the image we are uploading. Here, nosotros are using the middleware Multer to upload the photo to the server in a folder called ` uploads ` so we can process information technology.
    Add the following code to ` app.js `:

Javascript

var multer = require( 'multer' );

var storage = multer.diskStorage({

destination: (req, file, cb) => {

cb( null , 'uploads' )

},

filename: (req, file, cb) => {

cb( null , file.fieldname + '-' + Appointment.at present())

}

});

var upload = multer({ storage: storage });

  • Step 6: Now, load the Paradigm model by adding the following lawmaking to ` app.js `:

Javascript

var imgModel = require( './model' );

  • Footstep vii: Set up the handler for the Get request to our server. The response displays an HTML folio showing all the images stored in the database, and provides a UI for uploading new images.
    Add the post-obit code to ` app.js `:

Javascript

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

imgModel.discover({}, (err, items) => {

if (err) {

console.log(err);

res.status(500).send( 'An error occurred' , err);

}

else {

res.render( 'imagesPage' , { items: items });

}

});

});

  • Footstep 8: Handle the POST request that processes the grade data submitted by the user from our HTML UI.  This request volition have the new images being uploaded.
    Add the following code to ` app.js `:

Javascript

app.post( '/' , upload.single( 'image' ), (req, res, next) => {

var obj = {

name: req.body.name,

desc: req.body.desc,

img: {

data: fs.readFileSync(path.bring together(__dirname + '/uploads/' + req.file.filename)),

contentType: 'image/png'

}

}

imgModel.create(obj, (err, particular) => {

if (err) {

console.log(err);

}

else {

res.redirect( '/' );

}

});

});

  • Step 9: Configure the server to default port with the default of 3000 . The surroundings variable process.env.PORT is used if ready in your ` .env `.
    Add the post-obit code to ` app.js `:

Javascript

var port = process.env.PORT || '3000 '

app.heed(port, err => {

if (err)

throw err

panel.log(' Server listening on port', port)

})

  • Pace x: This is the HTML template for the "upload page". Notice that the src parameter for the <img> is not a typical URL. This format enables displaying the image stored in binary format in the Mongo database, and nosotros convert it to base64 so that the browser tin can render it.
    Add the following code to the ` views/imagesPage.ejs `:

HTML

<!DOCTYPE html>

< html lang = "en" >

< head >

< meta charset = "UTF-viii" >

< meta proper name = "viewport" content = "width=device-width, initial-scale=1.0" >

< title >Image Uploading</ title >

</ caput >

< body >

< h1 >To Upload Image on mongoDB</ h1 >

< hr >

< div >

< form action = "/" method = "POST" enctype = "multipart/grade-data" >

< div >

< characterization for = "proper noun" >Prototype Championship</ label >

< input type = "text" id = "name" placeholder = "Name"

value = "" name = "name" required>

</ div >

< div >

< label for = "desc" >Paradigm Description</ label >

< textarea id = "desc" name = "desc" value = "" rows = "2"

placeholder = "Description" required>

</ textarea >

</ div >

< div >

< label for = "paradigm" >Upload Image</ label >

< input type = "file" id = "image"

proper noun = "paradigm" value = "" required>

</ div >

< div >

< button type = "submit" >Submit</ button >

</ div >

</ form >

</ div >

< hr >

< h1 >Uploaded Images</ h1 >

< div >

<% items.forEach(function(image) { %>

< div >

< div >

< img src="data:image/<%=prototype.img.contentType%>;base64,

<%=image.img.information.toString('base64')%>">

< div >

< h5 ><%= epitome.name %></ h5 >

< p ><%= epitome.desc %></ p >

</ div >

</ div >

</ div >

<% }) %>

</ div >

</ body >

</ html >

  • Stride 11: Create the directory ` uploads ` that volition agree our uploaded images.  The code in Step 8 refers to this directory.
  • Step 12: Kickoff the server past running the command: ` nodemon app.js `

Output Open up your browser to http://localhost:3000/ .  You should now encounter:

Demo

 Congratulations!  You lot did it!


espinozamationsills2000.blogspot.com

Source: https://www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/

0 Response to "How to Upload File to Mongodb Compass"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel