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

前端 未结 2 1657
梦毁少年i
梦毁少年i 2020-12-08 04:30

I run a website that runs on a backend of nodeJS + mongoDB. Right now, I\'m implementing a system to store some icons (small image files) that will need to be in the databas

2条回答
  •  被撕碎了的回忆
    2020-12-08 05:11

    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!');
        });
    
        });
      });
    });
    

提交回复
热议问题