How To Store Image Into mongoDB Using Nodejs

By Yashwant Chavan, Views 29072, Last updated on 03-Mar-2019

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.

tags nodejs

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": "*"


    "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": [
    "author": "",
    "license": "MIT",
    "readmeFilename": ""

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'

            bucket.openUploadStream('dog.jpg')).on('error', function(error) {
            console.log('Error:-', error);
        }).on('finish', function() {
            console.log('File Inserted!!');

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


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
> db.images.files.find()
{ "_id" : ObjectId("5897fe852a14f91d48a66cbd"), "length" : 13291, "chunkSize" : 1024, "uploadDate" : ISODate("
2017-02-06T04:41:42.210Z"), "md5" : "c6f06b0bdc11b04d334c8cd85771d332", "filename" : "dog.jpg" }


Hi there! I am founder of and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][]