I've been struggling for a While now. I want to upload an image to mongo, not GridFS, I want tu save the image in a document.
This is what I have so far:
To upload the image:
News.image = function (id, req, res, cb) {
News.findById(id).then(function (news) {
if (!news) return cb({name: 'Not Found', status: '404', message: 'No news was found with given Id'});
if (!req.file) return cb({name: 'Bad Request', status: '400', message: 'No file was sent'});
var data = req.file.toString('base64');
app.models.Image.create({content: data, mimetype: req.file.mimetype}).then(function (img) {
cb(null, news);
}).catch(function (err) {
console.log(err);
cb(err);
});
});
};
Then I get this in the database:
{ "_id" : ObjectId("55ce4ae12f409cb685283a9f"), "mimetype" : "image/png", "content" : BinData(0,"W29iamVjdCBPYmplY3Rd") }
This is the code I use to retrieve the image:
Image.data = function (id, res, cb) {
Image.findById(id).then(function (img) {
if (!img) {
var err = new Error("Image not found");
err.statusCode = 404;
throw err;
}
var image = new Buffer(img.content, 'base64');
res.writeHead(200, {'Content-Type': 'image/png' });
res.end(image, 'binary');
}).catch(function (err) {
console.log(err.message);
cb(err);
});
};
And this is what I get back in my browser:
I just don't know if I'm storing the file the way I need to or I'm not getting it from the database the right way. How can I make this work?