难以理解gridfs和连接

时间:2018-10-28 12:16:02

标签: javascript node.js mongodb gridfs gridfs-stream

所以我看了这段视频:https://youtu.be/EVIGIcm7o2w

它解释了很多东西。但是问题是我已经有一个用Express创建的项目,因此我的连接是在app.js中完成的,如下所示:

// mongodb connection
var mongoose = require('mongoose');
var config = require('./globals/config');
mongoose.connect(config.db, {useNewUrlParser: true},).catch(e => console.log(e));

var db = mongoose.connection;
db.once('open', () => {
    console.log('Connected to mongodb. Go to http://localhost:3000 to open app');
});

现在,我想使用gridFS,在另一个文件中 将文件上传到我的数据库中,我尝试这样做:

var grid = require('gridfs-stream');
var mongoose = require('mongoose');
var fs = require('fs');
uploadFile(file) {
    var config = require('./config');
    mongoose.connect(config.db, {useNewUrlParser: true},).catch(e => console.log(e));
    var conn = mongoose.connection;
    grid.mongo = mongoose.mongo;
    const gfs = grid(conn.db);
    const writeStream = gfs.createWriteStream({
        filename: file.filename,
    });
    fs.createReadStream(file.path).pipe(writeStream);
    writeStream.on('close', function (file) {
        console.log(`${file.filename} written to the db`);
    });
}

但这没有意义,因为我要重新打开2个连接。我看了mongoose-gridfs,但它也显示以“ app.js”的形式使用它,没有跨文件的处理方式。如何在不打开2个连接并使用2个不同的js文件的情况下使用gridfs?

1 个答案:

答案 0 :(得分:1)

创建一个单独的模块,假设mygridfs.js并将函数放在module.exports中。将mongoose设置为此函数的参数:

var grid = require('gridfs-stream');
var fs = require('fs');
exports.uploadFile = function(file, mongoose) {
    grid.mongo = mongoose.mongo;
    const gfs = grid(mongoose.connection.db);
    const writeStream = gfs.createWriteStream({
        filename: file.filename,
    });
    fs.createReadStream(file.path).pipe(writeStream);
    writeStream.on('close', function (file) {
        console.log(`${file.filename} written to the db`);
    });
}

在主app.js文件中,仅需要以下模块:

var mygridfs= require("mygridfs");
mygridfs.uploadFile(file, mongoose);