我正在使用Grid保存并将二进制数据加载到mongoDB数据库。我正在使用nodejs。按照我能够找到的所有示例(非常相似)我的代码是:
router.get('/getlog',function(req,res) {
if (req.isAuthenticated())
{
var mongo = require('mongodb');
var Grid = require('gridfs-stream');
var db = new mongo.Db('logApp', new mongo.Server("127.0.0.1", 27017));
db.open(function (err) {
if (err) {
return handleError(err);
}
var gfs = Grid(db, mongo);
var readStream = gfs.createReadStream({
_id: req.query.id
}).pipe(res);
});
}
else
res.redirect('/home');
});
req.query.id是我需要的文件的ID。我得到的回应是:
MongoError: file with id 557aa98e6f1373cb11e8f294 not opened for writing
这没有意义,因为我不是在写,我正在读文件。
答案 0 :(得分:7)
该文件不存在。我查了一下:
gfs.exist({_id: req.query.id+''}, function (err, found) {
if (err) return handleError(err);
found ? console.log('File exists') : console.log('File does not exist');
res.send(found)
});
我使用了错误的ID。
答案 1 :(得分:1)
如果有人使用Mongoose,请确保将字符串ID包装为:
mongoose.Types.ObjectId(req.articleId)
否则MongoDB将无法识别该ID并将抛出错误。