Hey everyone, I've been working on this issue for nearly a day now and can't seem to figure it out. I'm utilizing multer's inMemory flag to upload an image from my website. My approach involves writing the buffer received from multer to GridFs (specifically GridStore).
Here is the code snippet for my multer:
product.js (route/controller)
var DB = rek('database');
var router = express.Router();
var multer = require("multer");
var uploadOptions = {inMemory:true, onFileUploadComplete: uploadDone}
router.post('/product/:productId/images/', multer(uploadOptions), uploadImageResponse);
function uploadDone(file) {
var options = {
name:file.name,
mode:"w+",
content_type:file.mimetype,
w: "majority",
chunkSize: 1024,
metadata:file
};
var GridStore = new DB.GridStore(DB.connection, file.name, "w+", options);
GridStore.open(function(err, GS){
if(err) throw err;
return GS.write(file.buffer, function(err, GS){
console.log("file written");
if(err) throw err;
return GS.close(function(err, result){
if(err) throw err
console.log(result);
})
})
});
}
Now you may be wondering where DB object comes from. Well, I simply add it to the mongoose object during initialization. Here is what the code looks like:
database.js
var mongoose = require("mongoose"),
mongooseTimestamps = require("mongoose-concrete-timestamps"),
autoIncrement = require("mongoose-auto-increment"),
config = require("../config"),
Grid = require("gridfs-stream");
mongoose.connect( config.database['development'].url + "" + config.database['development'].name );
var db = mongoose.connection;
db.once("open", function(err){
if(err) throw err
mongoose.GridStore = mongoose.mongo.GridStore
})
db.on("error",function(errMsg){
console.log("Error Connecting to Mongo: " + errMsg);
});
mongoose.set('debug', true);
mongoose.plugin(mongooseTimestamps);
autoIncrement.initialize(db);
module.exports = mongoose;
I've tried various approaches but keep getting no writes and no errors. Even the mongoose output log shows:
POST /product/1000/images 200 4.494 ms - 22
Mongoose: fs.chunks.ensureIndex([ [ 'files_id', 1 ], [ 'n', 1 ] ]) { w: 'majority' }
Mongoose: fs.files.find({ filename: '2b08f506ed277eda45f9fc400c098aa1.jpg' }) { readPreference: 'primary', w: 'majority' }
Mongoose: fs.chunks.find({ n: 0, files_id: ObjectId("54bb87aaabf2c0416a50c068") }) { readPreference: 'primary', w: 'majority' }
I'm puzzled by why it's performing a find operation when I'm trying to insert/write to GridFS. So far, I only get as far as the call to GridStore.open before the write never happens and no error is thrown.
Here are the things I've attempted so far:
- Using Multer's InMemory - same result
- Using Multer's dest attribute and piping the stream from fs to gridfs - same result
- Using the gridfs-stream module - Same result
- Used the Native GridFS/GridStoire - Same result.
Any assistance would be greatly appreciated.