How to store image into mongodb using nodejs

 Posted On  | Yashwant Chavan 

In this tutorial, You will learn how to STORE / INSERT image into MongoDB database using node.js, This step by step guide will help you to install MongoDB module, setup nodejs project and sample code to insert image / file into mongodb database using GridFS API.

Tools and Technologies

  • Node Version 6.9.4
  • Mongodb 3.3.12
  • Eclipse Mars

Nodejs Project Structure using Eclipse

How to store image into mongodb using nodejs - Eclipse Project Structure

Install nodejs mongodb module

package.json file contains the metadata information, Which helps to maintain node module dependencies. Add mongodb dependency in package.json or You can install mongodb module manually using npm install mongodb command.

"dependencies": {
    "mongodb": "*"
}

package.json

{
    "name": "NodejsExamples",
    "version": "0.1.0",
    "description": "NodejsExamples",
    "main": "node-mongodb-example.js",
    "scripts": {
        "test": "echo \"Error: no test specified! Configure in package.json\" && exit 1"
    },
    "repository": "",
    "dependencies": {
        "mongodb": "*"
    },
    "keywords": [
    "node.js",
    "eclipse",
    "nodeclipse"
  ],
    "author": "",
    "license": "MIT",
    "readmeFilename": "README.md"
}

Right click on package.json then select Run As -> npm install option. It will start downloading mongodb and dependent npm dependencies. Refer below log details.

Install nodejs mongodb module

mongodb npm installation log

Once installation is done, You will find mongodb module in "node_modules" folder.

NodejsExamples@0.1.0 C:\javaworkspace\NodejsExamples
`-- mongodb@2.2.22 
  +-- es6-promise@3.2.1 
  +-- mongodb-core@2.1.7 
  | +-- bson@1.0.4 
  | `-- require_optional@1.0.0 
  |   +-- resolve-from@2.0.0 
  |   `-- semver@5.3.0 
  `-- readable-stream@2.1.5 
    +-- buffer-shims@1.0.0 
    +-- core-util-is@1.0.2 
    +-- inherits@2.0.3 
    +-- isarray@1.0.0 
    +-- process-nextick-args@1.0.7 
    +-- string_decoder@0.10.31 
    `-- util-deprecate@1.0.2 

npm WARN NodejsExamples@0.1.0 No repository field.

Nodejs Insert Image into MongoDB database

require('mongodb') - Load the mongodb module to connect to mongob database.

require('fs') - Load the fs module to read image file from local drive.

require('mongodb').MongoClient - Create a new MongoClient instance.

mongoClient.connect() method is used to connect to MongoDB database using connection url.

new mongodb.GridFSBucket() - To use GridFS streaming API, You need to create a GridFSBucket instance. You can specify "chunkSizeBytes" and "bucketName", otherwise it will take default options.

The bucket has an openUploadStream() method which creates an upload stream for the input file.

var mongodb = require('mongodb');
var mongoClient = mongodb.MongoClient;
var fs = require('fs');

var url = 'mongodb://localhost:27017/technicalkeeda';

mongoClient.connect(url, function(err, db) {
    if (err) {
        console.log('Sorry unable to connect to MongoDB Error:', err);
    } else {

        var bucket = new mongodb.GridFSBucket(db, {
            chunkSizeBytes: 1024,
            bucketName: 'images'
        });

        fs.createReadStream('c:\\dog.jpg').pipe(
            bucket.openUploadStream('dog.jpg')).on('error', function(error) {
            console.log('Error:-', error);
        }).on('finish', function() {
            console.log('File Inserted!!');
            process.exit(0);
        });
    }
});

Run & Execute

Right click on node-mongodb-example.js file, select Run As -> Node Application option to execute the nodejs program.

Execute - How to store image into mongodb using nodejs

output

File Inserted!!

Mongodb Shell output

Above program creates two collections in your "technicalkeeda" database images.chunks and images.files. The "images.files" collection contains high-level metadata information of the stored files and "images.chunks" contains actual file content in the form of chunks.

> use technicalkeeda
switched to db technicalkeeda
> show collections
images.chunks
images.files
persons
system.indexes
system.profile
> db.images.files.find()
{ "_id" : ObjectId("5897fe852a14f91d48a66cbd"), "length" : 13291, "chunkSize" : 1024, "uploadDate" : ISODate("
2017-02-06T04:41:42.210Z"), "md5" : "c6f06b0bdc11b04d334c8cd85771d332", "filename" : "dog.jpg" }
>


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0300 seconds.