Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created April 17, 2012 19:14
Show Gist options
  • Save aheckmann/2408370 to your computer and use it in GitHub Desktop.
Save aheckmann/2408370 to your computer and use it in GitHub Desktop.
store/display an image in mongodb using mongoose/express
/**
* Module dependencies
*/
var express = require('express');
var fs = require('fs');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// img path
var imgPath = '/path/to/some/img.png';
// connect to mongo
mongoose.connect('localhost', 'testing_storeImg');
// example schema
var schema = new Schema({
img: { data: Buffer, contentType: String }
});
// our model
var A = mongoose.model('A', schema);
mongoose.connection.on('open', function () {
console.error('mongo is open');
// empty the collection
A.remove(function (err) {
if (err) throw err;
console.error('removed old docs');
// store an img in binary in mongo
var a = new A;
a.img.data = fs.readFileSync(imgPath);
a.img.contentType = 'image/png';
a.save(function (err, a) {
if (err) throw err;
console.error('saved img to mongo');
// start a demo server
var server = express.createServer();
server.get('/', function (req, res, next) {
A.findById(a, function (err, doc) {
if (err) return next(err);
res.contentType(doc.img.contentType);
res.send(doc.img.data);
});
});
server.on('close', function () {
console.error('dropping db');
mongoose.connection.db.dropDatabase(function () {
console.error('closing db connection');
mongoose.connection.close();
});
});
server.listen(3333, function (err) {
var address = server.address();
console.error('server listening on http://%s:%d', address.address, address.port);
console.error('press CTRL+C to exit');
});
process.on('SIGINT', function () {
server.close();
});
});
});
});
@BEN00262
Copy link

thanks for this, it really helped me

@mukulbawa
Copy link

Is there a way to find the path of the file and upload the file from the computer system ? I am trying to use the above mentioned code for storing images without using some extra package like Multer/Formidable etc. The code works fine if a static path is being used, but I wanted to check if someone can help me here to find the path dynamically.

@ridoansaleh
Copy link

@mukulbawa .. I think you could find the path from Client side / browser

@ardaorkin
Copy link

Thank you!

@apaar26
Copy link

apaar26 commented Jun 14, 2021

Is it possible to send all the images in the folder to the database?

@arpitsingla7
Copy link

How did we figure out "Adding a default Image path to Mongoose Schema."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment