空のファイルを読み込もうとしています。ディスクからファイルを読み込んで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()
コマンドを追加したので、問題がどこにあるのか簡単にわかります。