简体   繁体   中英

store files in mongoDB withour GridFS

我在使用MEAN堆栈开发的Web应用程序上工作,我需要在不调用GridF的情况下将文件存储在mongoDB中,因为后来这些文件很少,我做了很多研究,但我总是找到GridFS。

MongoDB has a Binary type . It's very easy to use:

var fs = require('fs');

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

// Connection url
var url = 'mongodb://localhost:27017/test';

// Connect using MongoClient
MongoClient.connect(url).then(function (db) {
    var collection = db.collection('bins');

    return collection.insert({
        name: 'image2',
        // the constructor takes a Buffer
        bin: new Binary(fs.readFileSync(__dirname + '/img.jpg'))
    }).then(function () {
        console.log('inserted');
        db.close();
    }).catch(function (err) {
        console.log(err);
    });
});

Retrieve the stored file:

MongoClient.connect(url).then(function (db) {
    var collection = db.collection('bins');

    return collection.findOne({ name: 'image2' }).then(function (doc) {
        console.log(doc);

        fs.writeFileSync(__dirname + '/out.jpg', doc.bin.buffer);

        db.close();
    })
});

Usage of the Binary type can be implicit. This will create a binary field too:

collection.insert({
    name: 'image2',
    bin: fs.readFileSync(__dirname + '/img.jpg')
})

Keep in mind that MongoDB documents have a 16MB total size limit .

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