Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store images in Mongodb serve them with Nodejs

I understand Mongodb can store images in two ways.

  1. in a regular document by storing the image as binary
  2. via Gridfs for managing larger images.

For simplicity and because the images I plan to server are small, I will go for option 1.

To serve the images to a browser I am using nodejs.

My question is how difficult will this be? How do you turn binary data to an actual image a browser will understand? What type of encoding is involved?

Could you point me to tutorials/examples elsewhere on the web?

By the way I know this may not be good idea for performance reasons, I plan to cache the images once served. I just want to avoid the file-system all-together.

like image 621
jamjam Avatar asked Jul 19 '12 20:07

jamjam


People also ask

Can you store images in MongoDB?

So for storing an image in MongoDB, we need to create a schema with mongoose. For that create the file `model. js` file and define the schema. The important point here is that our data type for the image is a Buffer which allows us to store our image as data in the form of arrays.


1 Answers

I would strongly advise against serving images from MongoDB.

It would be better to store them on a static filestore (S3) and maybe keep the path in MongoDB.


You would probably use base64 encoding to put the file into mongodb: http://www.greywyvern.com/code/php/binary2base64/ (or just base64 shell utility).

If you're just using regular documents then the performance cost is relatively low (so long as caching is good). If you're using a mixed database where you have GridFS and regular documents you're going to need a lot of RAM on your server(s) -- the GridFS queries will run completely differently from the document queries.

Converting the image might work like this:

var base64Data = imagefile.replace(/^data:image\/png;base64,/,""),
var dataBuffer = new Buffer(base64Data, 'base64');

// below line won't actually work but it's something along the lines of what you want:

db.foo.insert({magic: 123, etc... img: dataBuffer.toString()})
like image 66
Randall Hunt Avatar answered Sep 23 '22 05:09

Randall Hunt