MongoDB – GridFS Using Mongoose On Node.js

MongoDB and Node.js are often used together because of their shared use of JavaScript and its object notation (JSON & BSON). MongoDB is a type of NoSQL database will stores its data in documents. MongoDB stores data as BSON with a limitation of document size 16 MB, Where BSON is a binary serialization format used to store documents and make remote procedure calls in MongoDB. GridFS is MongoDB’s solution for storing and retrieving files that exceed the BSON-document size limit of 16 MB. Instead of storing a file in a single document, GridFS divides the file into parts, or chunks, and stores each chunk as a separate document.

Now, This post discuss about integration of GridFS Using Mongoose On Node.js, Where Mongoose is an object data modeling (ODM) library that provides a rigorous modeling environment for your data, enforcing structure as needed while still maintaining the flexibility that makes MongoDB powerful.

Source Code :

Snippet describes storing and retrieving files from database with GridFS. So, I have created a various routing to demonstrate GridFS functionality.

  • /write Writing a file from local path to MongoDB
  • /read Check if file exits, and then read the file from MongoDB
  • /delete Delete file from MongoDB
  • /meta Get file meta from MongoDB

By default GridFS will store files on default MongoDB collections(fs), If you need to store your files on custom collection, Replace GridFS options { filename: db_filename } to { filename: db_filename, root: 'myFiles' }. For more information about options see GridStore

Please leave your valuable comments/suggestions/feedback on below comment box if any.

Thank You !!

Siva Sankar

SIVA SANKAR, Working as a Software Engineer, Blogging is my hobby. I completed my Bachelors of Engineering (Computer Science Engineering) in Chennai, India. and my Master of Engineering (Embedded System Technologies) in Tamilnadu, India.

2 thoughts on “MongoDB – GridFS Using Mongoose On Node.js

  1. Hi, how do i specify a collection to save the file to? This example does not specify a collection so I’m wondering how this gets saved anywhere

    1. Hi Shaun Chua,
      By default GridFS will store files on default MongoDB collections(fs), If you need to store your files on custom collection, Replace GridFS options { filename: db_filename } to { filename: db_filename, root: ‘myFiles’ }.
      I also updated my article

      Thanks,
      Siva

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.