How to save file in Mongodb using Node.js

What the heck? file? why do you need to save file in document based database. Well, In this post I’m just going to show you how to save a file in mongodb and how retrieve it using mongodb nodejs native driver.

I assume that we all are familiar with Node.JS, mongodb. If you are not please go through using this link Mongodb native driver.

First we need mongodb npm package.We can install it using the below command

npm install mongodb  — save

next step is import library

var MongoClient = require(‘mongodb’).MongoClient;

Now how to connect and get db object. our db name is file_db.

MongoClient.connect(‘mongodb://’+username+’:’+password+’@localhost/file_db’, function(err, db){
if(err){
console.log("Please check you db connection parameters");
  }else{
console.log("Connection success");
// here we are going to write code for file
  }
});
Well I’m going to use mongodb Binary Class to convert large files in binary .We can import using
var Binary = require(‘mongodb’).Binary;

We need to fetch contents of file and then we have to convert into binary using Binary class. that code looks like this

var data = fs.readFileSync(file_path);
var insert_data = {};
insert_data.file_data= Binary(data);

Now we are ready to store this data into db using the following code.

var collection = db.collection(‘files’);
collection.insert(insert_data, function(err, result){
....

That’s It. yes we stored out file data into db. Now its time to show how to read that stored file data. To list out collections find command is used.

collection.findOne({}).toArray(function (err, documents) {
console.log(documents);
});

If we will get output like this

{ _bsontype: 'Binary',
sub_type: 0,
position: 7867,
buffer: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 c3 a4 c3 bc c3 b6 c3 ...> }

To convert buffered data to actual file we need to write this buffer into file. using below code.

collection.findOne({}).toArray(function(err, documents) {
if (err) console.error(err);
      fs.writeFile('file_name', documents[0].file_data.buffer, function(err){
if (err) throw err;
console.log('Sucessfully saved!');
});
});

That’s It. now we know how to store and get file content in mongodb. Note that mongodb document size limit is 16 megabytes. The above code is just for reference only.

Like what you read? Give Dinesh Uthakota a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.