In this blog post we will see how to integrate GridFS with mongoose.
Mongodb provides us with a very efficient way to store files directly in db rather than in file system. So basically what this means is, suppose you need to store an image file or an audio or video file you can directly store that in mongodb itself.
More details can be found here
Lets get in to the code on how to implement this. The library to use is https://www.npmjs.com/package/gridfs-stream
[code]
$ npm install gridfs-stream
[/code]
Writing a File
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://127.0.0.1/test');
var conn = mongoose.connection;
var fs = require('fs');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
conn.once('open', function () {
console.log('open');
var gfs = Grid(conn.db);
// streaming to gridfs
//filename to store in mongodb
var writestream = gfs.createWriteStream({
filename: 'mongo_file.txt'
});
fs.createReadStream('/home/etech/sourcefile.txt').pipe(writestream);
writestream.on('close', function (file) {
// do something with \`file\`
console.log(file.filename + 'Written To DB');
});
});
After above is done, you will see two collections added to the database ‘fs.chunks’ and ‘fs.files’
Reading a File
Reading a file is also easy, you need to know the filename or _id
//write content to file system
var fs\_write\_stream = fs.createWriteStream('write.txt');
//read from mongodb
var readstream = gfs.createReadStream({
filename: 'mongo_file.txt'
});
readstream.pipe(fs\_write\_stream);
fs\_write\_stream.on('close', function () {
console.log('file has been written fully!');
});
Deleting File
For Deleting a file you need to know the filename or _id
gfs.remove({
filename: 'mongo_file.txt'
}, function (err) {
if (err) return handleError(err);
console.log('success');
});
or
gfs.remove({
_id : '548d91dce08d1a082a7e6d96'
}, function (err) {
if (err) return handleError(err);
console.log('success');
});
File Exists
To check if a file exists or not
var options = {filename : 'mongo\_file.txt'}; //can be done via \_id as well
gfs.exist(options, function (err, found) {
if (err) return handleError(err);
found ? console.log('File exists') : console.log('File does not exist');
});
Access File Meta Data
gfs.files.find({ filename: 'mongo_file.txt' }).toArray(function (err, files) {
if (err) {
throw (err);
}
console.log(files);
});
Gfs can also be piped to a node http server easily to display images, audio file, etc for your web application.