So I watched this video: https://youtu.be/EVIGIcm7o2w
And it explained a lot of stuff. But the problem is I already have a project created with Express
so my connection is done in app.js like this:
// 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');
});
Now I want to use gridFS, in a different file to upload files to my db, and I tried this:
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`);
});
}
But this makes no sense, since I'm reopening 2 connections. I looked at mongoose-gridfs, but it also showed using it in sort of "app.js" no cross-file way of doing things. How do I use gridfs without opening 2 connections and using 2 different js files?
Create a separate module, let's say mygridfs.js
and place your function in module.exports
. Make mongoose
a parameter to this function:
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`);
});
}
In your main app.js
file, just require the module:
var mygridfs= require("mygridfs");
mygridfs.uploadFile(file, mongoose);