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();
});
});
});
});
@manisjosjs
Copy link

@kathar1223
Hey I did follow up your blog, And have to say, You have saved my day - but I want more help. I am able to upload image using the instructions provided but I do not know How to proceed with displaying the image on webpage or storing its location path into mongodb through moongoose.

@rafa-b
Copy link

rafa-b commented Dec 15, 2016

amazing

@UtsavAgrawal23
Copy link

I am able to save single image, but how we can save more than one images in mongodb and retrieve back

Copy link

ghost commented Feb 22, 2017

UtsavAgrawal23 You could store an array of objects in the image field in your schema:-

var imageSchema = new Schema({
img: { data: Buffer, contentType: String }
});

var productSchema = new Schema({
img: [imageSchema];
});

@socket-var
Copy link

Isn't readfilesync synchronous ? It shouldn't be used in web apps right ? If the image I huge then the entire IO is blocked right ?

@JSONRice
Copy link

JSONRice commented Mar 3, 2017

@saketh-bobby regardless of readfilesync this whole approach is only beneficial if images are 16Mb or less because of Mongo's retrieve restrictions. A better approach would be GridFS, but this approach also works well for smaller images, such as resized PNG's. I'll try to get a demo out later.

@lahong
Copy link

lahong commented Mar 8, 2017

@jsonwr a demo with this would be greatly appreciated thanks in advance

@Ainafidy
Copy link

Hi,can you help me in this code:

photo.controller--------------------------------------------

var mongoose = require('mongoose');
var PhotoModel = mongoose.model('Photos');
var fs =require('fs');

exports.addPhoto = function (req, res) {
var path='./Desktop/ExoInterfaceAPP/ic_friends.png'; //req.body.photo
if(fs.existsSync(path)) {
var photo = new PhotoModel();
photo._userid = req.body._userid;
photo.photo.data = fs.readFileSync(path);
photo.photo.contentType = 'image/png';
photo.as_profil = true;
photo.save((err, saved) => {
if (err) {
res.status(500).send(err);
} else {
console.log('sary ok');
res.json({
//data: saved,
status: true,
message: 'photo add success'
});
}
});
}

}

because my image in this path is not upload, my objectif is to upload the photo intruduct in "req.body.photo",
help me please

@kaushikpatel369
Copy link

i want to store images dynamically.
select image using file select and then store

@TarunKashyap18
Copy link

@octaviansoldea
Copy link

octaviansoldea commented Aug 7, 2017

At line 43, instead of

  var server = express.createServer();

I would rather use

  var server = express();

. In this context, see, also https://stackoverflow.com/questions/13499010/nodejs-express-launching-my-app-express-createserver-is-deprecated.

@ashrafkm
Copy link

Hi, I am using nodejs=mongodb. for the image upload, I want to give max size 5MB or 6MB. How can I do that? Can anyone tel me please..

here is my schema. for the coverImage, it allows max only 40kb size to upload the image but now I want to make it to 5MB.

 const nameSchema = Joi.object().keys({
description: Joi.string(), // .required(),
coverImage: Joi.string().Data: Buffer, // .required(), // ({ scheme: ['http', 'https'] }),
category: Joi.string(),
slug: Joi.string().regex(/^[a-z][a-z0-9-]*$/),
title: Joi.string(), // .required(),
price: Joi.number().integer(),
tag: Joi.object().keys({
    tag_name: Joi.string()
}),
publisher: Joi.object().keys({
    _id: Joi.string().hex().length(24),
    name: Joi.string().required()
}),
// published: Joi.string().isoDate().default(Date.now()),
rating: Joi.number().precision(2),
views: Joi.number().integer(),
hasErrors: Joi.boolean(),
allowSorting: Joi.boolean(),
allowAltered: Joi.boolean(),
choosetemplate: Joi.boolean(),
formErrors: Joi.object().keys({
    title: Joi.string(),
    description: Joi.string()
}),
includeCompleted: Joi.boolean(),
created_at: Joi.date().default(Date()),

});

@TheRobOne
Copy link

@kathar1223
Your solution doesn't store image in db only path to that image.
Am I right?

@TheRobOne
Copy link

Output of the db.as.find().pretty() gives very very long string. So do you think it is better to store user details in diffrent collection then its avatar?

@shoaibnoor95
Copy link

Is there any dependency of it?

@jaggu07
Copy link

jaggu07 commented Feb 6, 2018

works fine in localhost but fileread is not working in server
`events.js:160
throw er; // Unhandled 'error' event
^

Error: ENOENT: no such file or directory, open 'file:///Users/rda/Desktop/Appointment Booking.png'
at Error (native)
at Object.fs.openSync (fs.js:640:18)
at Object.fs.readFileSync (fs.js:508:33)`

Copy link

ghost commented Jun 14, 2018

Seems to me this is one of hardest back-end topics.

@Skycocoo
Copy link

Skycocoo commented Jul 17, 2018

So the working example to store image to local directory @TarunKashyap18 provided has few things to be noted:

  • to run the project: $ node app.js

  • the localhost its listening to is localhost:8000 instead of localhost:3000 noted in the comment (possibly didnt change much from the blog by @kathar1223.

  • to test the result: first open localhost:8000 to upload a random image; then open http://localhost:8000/images to check the _id of the stored image; to check the image: open http://localhost:8000/picture/(the _id you just checked)


A revised sample with detailed README could be found here

@ohasy
Copy link

ohasy commented Oct 16, 2018

Thanks a ton. I was searching a way to store files in mongo db for days.

@Arshitabhatt
Copy link

I can't thank you enough.

@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