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
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.
4 Comments
http)?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).