How to store images to MongoDB with Node.js

alven
2 min readAug 22, 2015

This post will teach you how to store images into a MongoDB database using the Mongoose ODM as well as retrieve and display those images.

To begin, we will create our server file. First we must install and require several npm packages.

var express = require(‘express’);
var fs = require(‘fs’);
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var multer = require('multer');

Next, we will connect to your MongoDB using the URL that your database is found at:

mongoose.connect(‘url_here’);

Once we have established a connection to our database and required all the necessary packages, we can now begin defining our server-side logic. We must first define our database schema

var Item = new ItemSchema(
{ img:
{ data: Buffer, contentType: String }
}
);
var Item = mongoose.model('Clothes',ItemSchema);

The important takeaway here is that our data type is a Buffer, which allows us to store our image as data in the form of arrays.

Next we must define the path of the image we are uploading. Here, we are using the middleware Multer to upload the photo on the server side.

app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename;
},
}));

Here, we use Multer to take a photo and put it in a folder called ‘uploads’ so we can easily access it later.

Finally, we must handle our post request to our database.

app.post(‘/api/photo’,function(req,res){
var newItem = new Item();
newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
newItem.img.contentType = ‘image/png’;
newItem.save();
});

Here, we create an instance of our Item model, and save the attributes of img.data and img.contentType. The img.data key will have a value of the image data, which will be an array of numbers representing our actual image. The img.contentType key specifies that we specifically have a png file. Finally, calling the .save() method will save this instance of our Item to our database. If you check your database find img.data as

<Binary Data>

that means you’re all set! You’ve successfully saved an image to a database.

--

--