如何在存储后从MongoDB中检索二进制文件?

我存储的文件类似于以下内容:

var pdfBinary = fs.readFileSync("myfile.pdf"); var invoice = {}; invoice.pdf = new mongo.Binary(pdfBinary); 

然后我把上面的文件插入到MongoDB中。 然后我尝试检索它类似于以下内容:

  collection.findOne({}, function(err, retrievedPDF) { fs.writeFile("myretrieved.pdf", retrievedPDF.pdf.buffer, function(err) { .... }); }); 

它作为一个零字节文件出来。 如果我console.log存储的文件,它看起来像这样:

 { pdf: { _bsontype: 'Binary', sub_type: 0, position: 0, buffer: <Buffer > }, _id: 53af545681a59758611937d7 } 

我已经通过了文档,我发现它有点混乱。 我做错了,我无法存储/检索文件?

您正试图读取一个空文件。 检查您的代码以从磁盘加载文件并检查PDF文件。

空的二进制文件将如下所示:

 > console.log(new mongodb.Binary("")); { _bsontype: 'Binary', sub_type: 0, position: 0, buffer: <Buffer > } 

有内容的二进制文件看起来像这样:

 { _bsontype: 'Binary', sub_type: 0, position: 7867, buffer: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 c3 a4 c3 bc c3 b6 c3 ...> } 

这是一个完整的例子,为我工作:

 var fs = require('fs'); var mongo = require('mongodb').MongoClient; var pdfBinary = fs.readFileSync("testout.pdf"); // print it out so you can check that the file is loaded correctly console.log("Loading file"); console.log(pdfBinary); var invoice = {}; invoice.pdf = new mongodb.Binary(pdfBinary); // set an ID for the document for easy retrieval invoice._id = 12345; mongo.connect('mongodb://127.0.0.1:27017/test', function(err, db) { if(err) console.log(err); db.collection('invoices').insert(invoice, function(err, doc){ // check the inserted document console.log("Inserting file"); console.log(doc); db.collection('invoices').findOne({_id : 12345}, function(err, doc){ if (err) console.error(err); fs.writeFile('testout.pdf', doc.pdf.buffer, function(err){ if (err) throw err; console.log('Sucessfully saved!'); }); }); }); }); 

我添加了console.log()命令,以便您可以轻松地看到问题出在哪里。

当然看起来好像在保存中出了问题。 这是一个完整的工作示例,可以比较:

 var fs = require('fs'), mongo = require('mongodb'), MongoClient = mongo.MongoClient, ObjectId = mongo.ObjectID, Binary = mongo.Binary; MongoClient.connect('mongodb://localhost/fs',function(err,db) { var name = "receptor.jpg"; var binData = fs.readFileSync(name); var object = {}; object.name = name; object.data = new Binary(binData); db.collection("test").findAndModify( { name: name }, [], object, { upsert:true }, function(err,data,newObj) { if ( data == null ) { console.log(newObj); } else { console.log(data); } db.collection("test").findOne({ name: name },function(err,data) { fs.writeFile("ouput.jpg",data.data.buffer,function(err) { console.log("done"); }); }); }); });