使用 GridFs 从 MongoDB 中提取文件 - id ### 的文件未打开以进行写入
Extract file from MongoDB using GridFs - file with id ### not opened for writing
我正在使用 Grid 将二进制数据保存和加载到 mongoDB 数据库。我正在使用节点。按照我能够找到的所有示例(非常相似),我的代码是:
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
这没有意义,因为我不是在写,而是在读文件。
文件不存在。我检查使用:
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。
如果有人在使用 Mongoose,请确保将字符串 ID 包装为:
mongoose.Types.ObjectId(req.articleId)
否则MongoDB将无法识别id并抛出错误。
我正在使用 Grid 将二进制数据保存和加载到 mongoDB 数据库。我正在使用节点。按照我能够找到的所有示例(非常相似),我的代码是:
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
这没有意义,因为我不是在写,而是在读文件。
文件不存在。我检查使用:
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。
如果有人在使用 Mongoose,请确保将字符串 ID 包装为:
mongoose.Types.ObjectId(req.articleId)
否则MongoDB将无法识别id并抛出错误。