Last active
August 29, 2015 14:05
-
-
Save joelabair/4d7aef6285fbe77732a9 to your computer and use it in GitHub Desktop.
GridFS Node Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'), | |
db = mongoose.connection.db, | |
GridStore = mongoose.mongo.GridStore, | |
stringifyObject = require('stringify-object'), | |
debug = require('debug')('myApp:MongoDB-GridFS'); | |
var collectionRoot = "TestArchive"; | |
var defaultQuery = { | |
"metadata.author": "Joel A. Bair", | |
"filename": "Summer Vacation.MOV" | |
}; | |
module.exports = function(query, callback) { | |
db.collection(collectionRoot + '.files', {strict:true}, function(err, files) { | |
if (err) debug(err) & return callback(err, null); | |
query = query || defaultQuery; | |
// .files collection | |
files.findOne(query, function(err, file) { | |
if (err) debug(err) & return callback(err, null); | |
// .chunks collection | |
var gs = GridStore(db, file._id, file.filename, "r", gsOptions); | |
gs.open(function(err, gs) { | |
if (err) debug(err) & return callback(err, null); | |
file.stream = gs.stream; | |
gs.seek(0, function(err, gs) { | |
if (err) debug(err) & return callback(err, null); | |
gs.read(function(err, fileData) { | |
if (err) debug(err) & return callback(err, null); | |
file.buffer = fileData; | |
if (callback) { | |
callback(null, file); | |
} | |
}); | |
}); | |
}); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment