GridFS Using Mongoose – NodeJS

In this blog post we will see how to integrate GridFS with mongoose.

Mongodb provides us with a very efficient way to store files directly in db rather than in file system. So basically what this means is, suppose you need to store an image file or an audio or video file you can directly store that in mongodb itself.
More details can be found here

Lets get in to the code on how to implement this. The library to use is

$ npm install gridfs-stream

Writing a File

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var conn = mongoose.connection;

var fs = require('fs');

var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;

conn.once('open', function () {
    var gfs = Grid(conn.db);

    // streaming to gridfs
    //filename to store in mongodb
    var writestream = gfs.createWriteStream({
        filename: 'mongo_file.txt'

    writestream.on('close', function (file) {
        // do something with `file`
        console.log(file.filename + 'Written To DB');

After above is done, you will see two collections added to the database ‘fs.chunks’ and ‘fs.files’

Reading a File

Reading a file is also easy, you need to know the filename or _id

//write content to file system
var fs_write_stream = fs.createWriteStream('write.txt');

//read from mongodb
var readstream = gfs.createReadStream({
     filename: 'mongo_file.txt'
fs_write_stream.on('close', function () {
     console.log('file has been written fully!');

Deleting File

For Deleting a file you need to know the filename or _id

filename: 'mongo_file.txt'
}, function (err) {
  if (err) return handleError(err);


_id : '548d91dce08d1a082a7e6d96'
}, function (err) {
  if (err) return handleError(err);

File Exists

To check if a file exists or not

var options = {filename : 'mongo_file.txt'}; //can be done via _id as well 
gfs.exist(options, function (err, found) {
  if (err) return handleError(err);
  found ? console.log('File exists') : console.log('File does not exist');

Access File Meta Data

gfs.files.find({ filename: 'mongo_file.txt' }).toArray(function (err, files) {
    if (err) {
         throw (err);

Gfs can also be piped to a node http server easily to display images, audio file, etc for your web application.