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

Hoa*_*Hoa 7 mongodb node.js

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

var pdfBinary = fs.readFileSync("myfile.pdf");
var invoice = {};
invoice.pdf = new mongo.Binary(pdfBinary);
Run Code Online (Sandbox Code Playgroud)

然后我将上面的文档插入MongoDB.然后我尝试检索它类似于以下内容:

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

    }); 
Run Code Online (Sandbox Code Playgroud)

它作为零字节文件出现.如果我在console.log中存储文件,它看起来如下所示:

{ pdf: 
 { _bsontype: 'Binary',
   sub_type: 0,
   position: 0,
   buffer: <Buffer > },
_id: 53af545681a59758611937d7 }
Run Code Online (Sandbox Code Playgroud)

我已经阅读了文档,我发现它有些令人困惑.我无法存储/检索文件,我做错了什么?

Chr*_*n P 8

你正在尝试读取一个空文件.检查代码以从磁盘加载文件并检查PDF文件.

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

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

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

{ _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 ...> }
Run Code Online (Sandbox Code Playgroud)

这是一个适合我的完整示例:

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!');
      });
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

我添加了console.log()命令,因此您可以轻松查看问题所在.