Tutorial: MongoDB GridFS Support

MongoDB GridFS Support

flitter-gridfs

MongoDB GridFS is awesome. But, the learning curve is pretty high, and it can be messy to work with. flitter-gridfs is a wrapper for GridFS that provides a Mongoose model in Flitter to make it easier to interact with.

Installation

Install flitter-gridfs to your Flitter application:

yarn add flitter-grifs

Then, add the unit to your applications Units.flitter.js file, in the "Pre-Routing Custom Units" section:

    'GridFs'        : new (require('flitter-gridfs/GridFsUnit'))(),

Getting Started

The package provides the gridfs::file model to the Flitter application.

Save a file to GridFS

const File = _flitter.model('gridfs::file')
const file = new File({
    name: 'foobar.txt',
    content_type: 'text/plain',
})

await file.save()
await file.write_from_file({ filepath: '/tmp/grid/foobar.txt' })

Save a GridFS file to a local file

const File = _flitter.model('gridfs::file')
const file = await File.findOne({ name: 'foobar.txt' })

await file.write_to_file({ filepath: '/tmp/grid/baz.txt' })

Send a GridFS file as an Express response

class SomeFlitterController {
    async send_file(req, res, next){
        const File = _flitter.model('gridfs::file')
        const file = await File.findOne({ name: 'foobar.txt' })
        return file.send_to_response(res)
    }
}

Other Stuff

Get the GridFSBucketReadStream instance directly:

const File = _flitter.model('gridfs::file')
const file = await File.findOne({ name: 'foobar.txt' })

const read_stream = file.get_read_stream()

Get the GridFSBucket directly:

const File = _flitter.model('gridfs::file')
const file = await File.findOne({ name: 'foobar.txt' })

const bucket = file.grid()

Get the native GridFS files collection:

Note that this is not the collection of File model instance. This is the underlying files collection used by flitter-gridfs. Most of the time you shouldn't need this.

const File = _flitter.model('gridfs::file')

const collection = await File.files()