NodeJS – use Mongoose to save Files/Images to MongoDB

In the tutorial, we will show how to build a NodeJS application to save files/images to MongoDB database using Mongoose.

Related posts:
Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose

Mongoose save files/images to MongoDB

Firstly, we define a Mongoose model for files/images with Buffer data as below:

To read/write data of file/image, we use fs.readFileSync('/path/to/file') and fs.writeFileSync('/path/to/file', functions of NodeJS file-system module.

Below segment code is used to store file/image to MongoDB:


We build a NodeJS project as below structure:

Setting up NodeJS project

Init NodeJs project by commandline: npm init:

Install Mongoose dependency:

-> package.json file:

Mongoose Image model

./app/model/img.model.js file:

MongoDB configuration

./app/config/mongodb.config.js file:

Static assets

Create a folder ./static/assets that contains 2 sub folders: images, tmp
images folder contains files for saving to MongoDB.
tmp folder contains files that getting from MongoDB after saving.

NodeJS application

./app.js file:

Run & Check results

Run NodeJS application:
-> Server Logs:

-> MongoDB’s collections:



By JavaSampleApproach | May 2, 2018.

Related Posts

Got Something To Say:

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