1

I am building a personal project in Node, and I want my users to be able to upload 'cover' photos. The approach I am using right now is to save these images to my fs, and just add the path to that image in a MongoDB database. So if a user adds an image I add that image to my images folder with the name lets say userID.jpg, and I save "/public/images/userID.jpg" as a string in my database. I have a feeling that this approach might not be the most efficient. Should I be directly saving it to the database? What are the advantages or disadvantages ?

1 Answer 1

1

Storing your images as files is actually pretty efficient (unless we're talking about 10's of K's of images, but still). Also, on the serving side, the images would probably be handled by something like express.static() (assuming that you're using Express), which is also quite lightweight.

However, if you eventually want to be a bit more scalable, you can take a look at using GridFS, which implements a file-system like storage on top of MongoDB. I use gridfs-stream for something similar (uploads/downloads) and it works fine.

If the images are small enough (smaller than about 16MB, which is the size limit for BSON documents), you might not even need to use GridFS and just store the images as Binary type.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks a lot for the quick response.. can you please explain where exactly I should be using express.static() ?
Are you using Express to handle your uploads? Or do you use another framework (or perhaps just plain http)?
I am using express.. but I was making an ajax request to be able to directly show the image back in the frontend
Oh right, in that case, you could try adding this somewhere in your middleware initialisation: app.use(express.static(__dirname + '/public')); that would make the images available (from HTML) as /images/userID.jpg (see also the docs on connect.static, which is the same as express.static).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.