I caught the MongoDB bug recently as part of my own exercise to learn more than 1 database system in my development life somewhat similar to ‘7 databases in 7 weeks’ but less severe regime.
I realised that it is possible to store file uploads within a mongodb instance using its gridfs file system so decided to have a go. I first setup carrierwave and carrierwave-mongoid but it seems that the latest versions of both gems do not work well with the mongoid version 3+ gems due to api changes. After several attempts and google searches I gave up and was in the process of rolling back mongoid gem to 2+ when I suddenly thought of Dragonfly the fantastic file uploader by Mark Evans of new bamboo
One of the coolest features of Dragonfly is the ability to have a single upload such as an image and being able to chain various processing options to it or to scale it on the fly. This beats the carrierwave approach of declaring versions in my opinion
To get this to work I have to do the following:
- Declare dragonfly as a gem dependency in your gemfile. Put rack-cache above it if you wish to cache the assets
- Create a dragonfly initialiser file documented here in the docs. Now Dragonfly::DataStorage::MongoDataStore has a require for the mongo gem so you need to update your gemfile to also include the mongo, bson and bson_ext gems. I put these before the dragonfly and rack-cache. To configure the datastore I decided to use the more verbose approach and declare everything manually as documented here.
- Within your model declare the relevant accessors. In my case I have a User model which needs to have its own avatar so I added in the following:
Restart your application server and you should have a working version of file uploads using GridFS with mongodb. Dragonfly also seems to deal with the streaming of the uploads back to the front end without any need to write your own rack middleware to deal with it.
Hope this helps someone with starting with file uploads in mongo. I am still learning about the system so any feedback is greatly welcomed.