Storing some small (under 1MB) files with MongoDB in NodeJS WITHOUT GridFS

前提是你 提交于 2019-11-28 05:24:18

If your images truly are small enough to not be a problem with document size and you don't mind a little amount of extra processing, then it's probably fine to just store it directly in your collection. To do that you'll want to base64 encode the image, then store it using mongo's BinData type. As I understand it, that will then save it as a BSON bit array, not actually store the base64 string, so the size won't grow larger than your original binary image.

It will display in json queries as a base64 string, which you can use to get the binary image back.

I have been looking for the same thing. I know this post is old , but perhaps i can help someone out there.

var fs = require('fs');
var mongo = require('mongodb').MongoClient;
var Binary = require('mongodb').Binary;

var archivobin = fs.readFileSync("vc.exe"); 
// print it out so you can check that the file is loaded correctly
console.log("Loading file");
console.log(archivobin);

var invoice = {};
invoice.bin = Binary(archivobin);

console.log("largo de invoice.bin= "+ invoice.bin.length());
// set an ID for the document for easy retrieval
invoice._id = 12345; 
  mongo.connect('mongodb://localhost:27017/nogrid', function(err, db) {
  if(err) console.log(err);
     db.collection('invoices').insert(invoice, function(err, doc){
    if(err) console.log(err);
  // 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('vcout.exe', doc.bin.buffer, function(err){
          if (err) throw err;
          console.log('Sucessfully saved!');
    });

    });
  });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!