Reputation: 96
Im trying to use gridfs to upload files into my system. I am facing an issue in trying to connect mongodb to gridfs im only using the gridfs connection from its docs. app file :
// DB Config
const db = require("./mongoos1.js");
// Connect to MongoDB
const conn = db.connect((err) => {
if (err) {
console.log('unable to connect to database');
process.exit(1);
}
else {
app.listen(5000, () => {
console.log('connected to database, app listening on port 5000');
});
}
});
// Init gfs
let gfs;
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
});
Mongoose file:
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
const dbname = "FYP";
const url = "mongodb://localhost:27017/FYP";
const mongoOptions = { useNewUrlParser: true };
const state = {
db: null
};
const connect = (cb) => { // connect method
if (state.db) //if there is connection
cb();
else { // if there isn't
MongoClient.connect(url, mongoOptions, (err, client) => { // we use mongoclient to connect
if (err)
cb(err);
else {
state.db = client.db(dbname); // if no error , set state
cb();
}
});
}
}
module.exports = { connect }; //exposing methods
am i making a mistake somewhere?
Upvotes: 0
Views: 2643
Reputation: 1045
mongoDB connection is not the same as connection that is returned from createConnection
You should connect your event handler to the connection as returned by createConnection(), and not to mongoose.connection
Or move your code from 'once open' inside .connection() callback function.
Upvotes: 2