How to Store Images into Specified Collections in MongoDB

2.8k views Asked by At

I know it is possible to save binary files into using MongoDB using the "mongofiles" utility.

Is there any way to store Images into a specified collection, not in db.fs.files?

I want to create an users collection which is using to store user details along with their profile pic like this:

{
    "_id" : "USR_1",
    "username"  : "willsmith123",
    "firstname" : "will",
    "lastname"  : "smith",
    "status"    : "ACTIVE",
    "image"     : { 
             "_id"        : ObjectId("558be8062f194d2587000001")
             "chunkSize"  : 261120,
             "uploadDate" : ISODate("2015-06-25T10:20:47.105Z"),
             "length"     : 25038,
             "md5"        : "b1d38a0b2ccde6da71fd6ae8fe2f637f",
             "filename"   : "mylogo.png"
                  }
}

How can I have a collection like this, which maintain relation between users and their images?

2

There are 2 answers

0
karthick On BEST ANSWER

Note:

Database is for data

FileSystem for files

Choice Matters

Use GridFs or else use the below stuff

Instead of saving the embedded document

         "image"     : { 
              "chunkSize"  : 261120,
              "uploadDate" : ISODate("2015-06-25T10:20:47.105Z"),
              "length"     : 25038,
              "md5"        : "b1d38a0b2ccde6da71fd6ae8fe2f637f",
              "filename"   : "mylogo.png"
          }

Just save the reference of the image as below

{
   "_id" : "USR_1",
   "username"  : "willsmith123",
   "firstname" : "will",
   "lastname"  : "smith",
   "status"    : "ACTIVE",
   "imageRef"     : "unique id (objectID)"
}

Use the imageRef to get or set the image.

1
Kyaw Minn On
  1. When you upload image , writestream create image id. At the same time , you can't save image id to another collection.
  2. If you create custom id, it's not safe and problem for many images.
  3. You can save image info in the document files.metadata