Wednesday, 12 April 2017

Extracting BLOBS (png/jpg) from Mongodb with nodejs

While Google returns lots of instructions to stuff blobs (like images) into MongoDB (mainly with mongoose.Schema), there seems to be very little about reading and extracting.

I chose not to use GridFS to save my blobs, as these are small (<1MB) thumbs and it doesn't appear to help extract or unencode my file.

By way of example, I use Mongoose to save() a small thumbnail image into a Collection like so,

     mongoose.connect(url);
     var newItem = new Item(); 
     newItem.img.data = fs.readFileSync(picture);
     newItem.img.contentType = 'image/png';
     newItem.filename = 'mythumb.png';
     newItem.description= 'A small pic';
     newItem.save();

I can see the new item in the Collection,

{
    "_id": {
        "$oid": "58ee89a4e88da612d3561c9f"
    },
    "description": "A small pic",
    "filename": "mythumb.png",
    "img": {
        "contentType": "image/png",
        "data": "<Binary Data>"
    },
    "__v": 0
}

I can extract this item with a simple find().toArray() and see my encoded image,

contentType:"image/png"
data:"/9j/4AAQSkZJRgABAQAASABIA...<snip>..."

My question is, how to turn this back into a useable image file?

Thanks



via Colin

No comments:

Post a Comment