参考这篇文章:
Node.js File Upload (Express 4, MongoDB, GridFS, GridFS-Stream)
我基本上正在做的事情似乎是我应该保存文件上传到Mongo GridFS的一切。但是,似乎没有任何东西被保存在Mongo GridFS数据库中(没有块或文件)。我正在使用busboy来解析进入的多部分数据,我已经验证我通过Mongoose连接到Mongo数据库...我只是在寻找一个评论,看看为什么没有保存!
router.route('/doc')
.post(function(req, resp, next) {
var gfs = gridfs(mongoose.connection);
var bb = new busboy({
headers: req.headers
});
bb.on('file', function(fieldname, file, filename, encoding, mimetype) {
var doc = new DocumentMeta();
doc.setFileName(filename);
doc.setMimetype(mimetype);
doc.setEncoding(encoding);
doc.insert(function(err) {
if(!err) {
var ws = gfs.createWriteStream({
_id: mongoose.Types.ObjectId().toString(),
filename: filename,
mode: 'w',
content_type: mimetype
});
ws.on('close', function(file) {
console.log('Doc Written to DB');
});
file.on('data', function(data) {
console.log('GOT DATA');
});
file.pipe(ws);
} else {
resp.json({success:false, msg: 'Error Creating Doc', data : { error : err.message }});
}
});
});
bb.on('finish', function() {
resp.json({success:true, msg: 'Successfully Uploaded Doc'});
});
req.pipe(bb);
});
我得到以下控制台输出:
Mongoose: fs.files.ensureIndex([ [ 'filename', 1 ] ]) { w: 1 }
GOT DATA
Mongoose: fs.chunks.ensureIndex([ [ 'files_id', 1 ], [ 'n', 1 ] ]) { w: 1 }
Mongoose: fs.files.findOne({ _id: ObjectId("56a16a383f6fbc877550752f") }) { w: 1, readPreference: 'primary' }
Mongoose: fs.chunks.remove({ files_id: ObjectId("56a16a383f6fbc877550752f") }) { w: 1, readPreference: 'primary' }
GOT DATA
GOT DATA
GOT DATA
GOT DATA
GOT DATA
POST /doc 200 756.218 ms - 50
我注意到mongoose正在调用fs.chunks.remove ...为什么要尝试删除块?在GridFS写入流上也从不调用“关闭”,所以我从不按预期输出“Doc Writed to DB”...
非常感谢任何指导!谢谢!