简体   繁体   中英

How to save a File in MongoDB database?

I'm making a small project storing a document file in MongoDB database. I heard that document files cannot be stored directly in MongoDB whereas we can store it in google drive or dropbox or etc., and we can reference it from there. Is that correct or wrong if it's wrong can anyone help me out with this project? I just a made reference to understand my project here is my plunker link please have a look and let me know the best approach?

<https://plnkr.co/edit/RwjmCynuvzj8reqv2pw6?p=preview>

You can store large files in MongoDB. Have a look at https://www.mongodb.com/blog/post/storing-large-objects-and-files-in-mongodb

MongoDB stores objects in a binary format called BSON. BinData is a BSON data type for a binary byte array. However, MongoDB objects are typically limited to 4MB in size. To deal with this, files are “chunked” into multiple objects that are less than 4MB each. This has the added advantage of letting us efficiently retrieve a specific range of the given file.

You can try the below code -

mongoose.connect(<mongodbUri>);

var lineList = fs.readFileSync(<filepath>).toString().split('\n');
lineList.shift();

//creating schema for database. As an example you can see below - 
var schemaKeyList = ['EmployeeID', 'Designation', 'Address'];

var EmployeeSchema = new mongoose.Schema({
    EmployeeID: String,
    Designation: String,
    Address: String

});

//create model for schema
var EmpDoc = mongoose.model('Employees', EmployeeSchema );

function queryAllEntries () {
    EmpDoc .aggregate(
        {$group: {_id: '$EmployeeID', oppArray: {$push: {
            Designation: '$Designation',
            Address: '$Address'
            }}
        }}, function(err, qDocList) {
        //console.log(util.inspect(qDocList, false, 10));
        process.exit(0);
    });
}


function createDocRecurse (err) {
    if (err) {
        console.log(err);
        process.exit(1);
    }
    if (lineList.length) {
        var line = lineList.shift();
        var doc = new EmpDoc();
        line.split(',').forEach(function (entry, i) {
            doc[schemaKeyList[i]] = entry;
        });
        doc.save(createDocRecurse);
    } else {
        queryAllEntries();
    }
}

createDocRecurse(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM