Storing Images in MongoDB Using NodeJS
The BSON type binData
I hope that when you first see the title you might be assuming that you will see some concept related to GridFS
. But sorry! not at all. If you are looking for something that relates to GridFS this article is NOT for you. Because we are not going to touch GridFS. Instead, we will learn about one of MongoDB BSON types known as Binary data
alias binData.
Please check the list of BSON types that MongoDB supports.
I will probably come up with a different comprehensive article on GridFS. But here, let me also mention the three typical ways to store images in MongoDB.
- Using GridFS: Provides convenient API to store and retrieve BSON
Binarydata
that exceeds MongoDB’s BSON-document size limit of 16 MiB. It splits the file into smaller chunks and stores them as separate documents. Check here for more information onGridFS
. - Within Document: Images less than of size 16MB can be stored in the document itself using the BSON type
Binarydata
. - Storing Reference URLs: Referencing the URLs where the images are stored (like AWS S3) in the document with the conventional
String
type.
In this article, we will look at the second approach.
The most suitable scenario where we can go with the second approach is: Storing an avatar or a profile picture of a user as part of the profile.