rob*_*cks 2 mongoose mongodb node.js gridfs express
我的应用程序使用节点0.10.1,表达3.1.1,mongoose 3.6.4,mongo 2.4.1和gridfs-stream 0.4.0.
我已经使用共享连接设置了mongoose和gridfs-stream,如下所示:
/************* app.js ***************/
//Added this in edit to show setup of mongoose and gridfs-stream
var mongoose = require("mongoose");
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
global.conn = mongoose.createConnection(dbUri);
conn.once('open', function(){
global.gfs = Grid(conn.db);
});
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用gridfs-stream上传/下载文件.我上传的内容如下:
exports.uploadFile = function(req, res){
var file = req.files.upload;
var docId = mongoose.Types.ObjectId(req.query.docId);
var filename = req.query.ileName;
var contentType = file.type;
if(!file) return res.send({result: 'NO_FILE_UPLOADED'});
var writestream = gfs.createWriteStream({
_id: docId,
filename: filename,
mode: 'w',
root: 'documents'
});
// more here but ommitted
};
Run Code Online (Sandbox Code Playgroud)
docId来自mongo文档的ObjectId.
上传似乎有效.我可以使用mongo控制台查看上传的文件:
db.documents.files.findOne()
{
"_id" : ObjectId("5167604d1b63f2541400003d"),
"filename" : "borrower1.fnm",
"contentType" : "binary/octet-stream",
"length" : 3473,
"chunkSize" : 262144,
"uploadDate" : ISODate("2013-04-12T15:43:06.723Z"),
"aliases" : null,
"metadata" : null,
"md5" : "04c85fe5e9ba0e798fd5eb90f1cb62be"
}
Run Code Online (Sandbox Code Playgroud)
当我尝试下载文件时,使用以下内容:
exports.downloadFile = function(req, res){
var docId = mongoose.Types.ObjectId(req.query.docId);
var readstream = gfs.createReadStream({_id: docId});
readstream.pipe(res);
};
Run Code Online (Sandbox Code Playgroud)
抛出以下错误:
Error: 5167604d1b63f2541400003d does not exist
Run Code Online (Sandbox Code Playgroud)
当我尝试使用似乎存储在gridfs db中的_id直接从mongo控制台检索文件时,它返回null.但是如果我尝试使用文件名检索文件,mongo控制台将检索该文件.
gridfs中上传文件的_id是否可以使用相关mongo文档的_id设置?如果是这样,我的代码怎么不正确?如果没有,有没有办法让网格生成id并获取分配的ID,以便我可以将其存储在相关的mongo文档中?
谢谢你的帮助!
抢
我将回答我自己的问题,因为我在浏览mongoose server.js和gridfs-stream的源代码时找到了答案.
您可以将相关文档的ObjectId用于存储文件的ObjectId.
但是,如果您在上传时提供"root"选项,则还需要使用它在下载代码中使用它.否则,mongoose假定集合是基本集合.
这样可行:
exports.uploadFile = function(req, res){
var file = req.files.upload;
var docId = mongoose.Types.ObjectId(req.query.docId);
var filename = req.query.ileName;
var contentType = file.type;
if(!file) return res.send({result: 'NO_FILE_UPLOADED'});
var writestream = gfs.createWriteStream({
_id: docId,
filename: filename,
mode: 'w',
root: 'documents'
});
// more here but ommitted
};
exports.downloadFile = function(req, res){
var id = gfs.tryParseObjectId(req.query.docId);
//note that options now includes 'root'
var options = {_id: id, root: 'documents'};
try{
gfs.createReadStream(options).pipe(res);
} catch(err){
console.log(err);
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3680 次 |
| 最近记录: |