How to properly reuse connection to Mongodb across NodeJs application and modules
up vote
62
down vote
favorite
I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app starts and reused between modules. My current idea of the best way is that server.js
(main file where everything starts) connects to database and creates object variable that is passed to modules. Once connected this variable will be used by modules code as necessary and this connection stays open. E.g.:
var MongoClient = require('mongodb').MongoClient;
var mongo = {}; // this is passed to modules and code
MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) {
if (!err) {
console.log("We are connected");
// these tables will be passed to modules as part of mongo object
mongo.dbUsers = db.collection("users");
mongo.dbDisciplines = db.collection("disciplines");
console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules
} else
console.log(err);
});
var users = new(require("./models/user"))(app, mongo);
console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined
then another module models/user
looks like that:
Users = function(app, mongo) {
Users.prototype.addUser = function() {
console.log("add user");
}
Users.prototype.getAll = function() {
return "all users " + mongo.dbUsers;
}
}
module.exports = Users;
Now I have horrible feeling that this is wrong so are there any obvious problems with this approach and if so how to make it better?
javascript node.js mongodb express
add a comment |
up vote
62
down vote
favorite
I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app starts and reused between modules. My current idea of the best way is that server.js
(main file where everything starts) connects to database and creates object variable that is passed to modules. Once connected this variable will be used by modules code as necessary and this connection stays open. E.g.:
var MongoClient = require('mongodb').MongoClient;
var mongo = {}; // this is passed to modules and code
MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) {
if (!err) {
console.log("We are connected");
// these tables will be passed to modules as part of mongo object
mongo.dbUsers = db.collection("users");
mongo.dbDisciplines = db.collection("disciplines");
console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules
} else
console.log(err);
});
var users = new(require("./models/user"))(app, mongo);
console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined
then another module models/user
looks like that:
Users = function(app, mongo) {
Users.prototype.addUser = function() {
console.log("add user");
}
Users.prototype.getAll = function() {
return "all users " + mongo.dbUsers;
}
}
module.exports = Users;
Now I have horrible feeling that this is wrong so are there any obvious problems with this approach and if so how to make it better?
javascript node.js mongodb express
The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
– Salvador Dali
Jul 8 '14 at 1:22
Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection likemodule.exports = mongoist(connectionString);
. (Read aboutconnectionString
in MongoDB Manual.)
– Alexandr Nil
Oct 1 '17 at 19:37
add a comment |
up vote
62
down vote
favorite
up vote
62
down vote
favorite
I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app starts and reused between modules. My current idea of the best way is that server.js
(main file where everything starts) connects to database and creates object variable that is passed to modules. Once connected this variable will be used by modules code as necessary and this connection stays open. E.g.:
var MongoClient = require('mongodb').MongoClient;
var mongo = {}; // this is passed to modules and code
MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) {
if (!err) {
console.log("We are connected");
// these tables will be passed to modules as part of mongo object
mongo.dbUsers = db.collection("users");
mongo.dbDisciplines = db.collection("disciplines");
console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules
} else
console.log(err);
});
var users = new(require("./models/user"))(app, mongo);
console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined
then another module models/user
looks like that:
Users = function(app, mongo) {
Users.prototype.addUser = function() {
console.log("add user");
}
Users.prototype.getAll = function() {
return "all users " + mongo.dbUsers;
}
}
module.exports = Users;
Now I have horrible feeling that this is wrong so are there any obvious problems with this approach and if so how to make it better?
javascript node.js mongodb express
I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app starts and reused between modules. My current idea of the best way is that server.js
(main file where everything starts) connects to database and creates object variable that is passed to modules. Once connected this variable will be used by modules code as necessary and this connection stays open. E.g.:
var MongoClient = require('mongodb').MongoClient;
var mongo = {}; // this is passed to modules and code
MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) {
if (!err) {
console.log("We are connected");
// these tables will be passed to modules as part of mongo object
mongo.dbUsers = db.collection("users");
mongo.dbDisciplines = db.collection("disciplines");
console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules
} else
console.log(err);
});
var users = new(require("./models/user"))(app, mongo);
console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined
then another module models/user
looks like that:
Users = function(app, mongo) {
Users.prototype.addUser = function() {
console.log("add user");
}
Users.prototype.getAll = function() {
return "all users " + mongo.dbUsers;
}
}
module.exports = Users;
Now I have horrible feeling that this is wrong so are there any obvious problems with this approach and if so how to make it better?
javascript node.js mongodb express
javascript node.js mongodb express
edited Jul 8 '14 at 6:39
tereško
52.2k1976135
52.2k1976135
asked Jul 8 '14 at 0:22
spirytus
3,66164966
3,66164966
The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
– Salvador Dali
Jul 8 '14 at 1:22
Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection likemodule.exports = mongoist(connectionString);
. (Read aboutconnectionString
in MongoDB Manual.)
– Alexandr Nil
Oct 1 '17 at 19:37
add a comment |
The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
– Salvador Dali
Jul 8 '14 at 1:22
Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection likemodule.exports = mongoist(connectionString);
. (Read aboutconnectionString
in MongoDB Manual.)
– Alexandr Nil
Oct 1 '17 at 19:37
The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
– Salvador Dali
Jul 8 '14 at 1:22
The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
– Salvador Dali
Jul 8 '14 at 1:22
Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection like
module.exports = mongoist(connectionString);
. (Read about connectionString
in MongoDB Manual.)– Alexandr Nil
Oct 1 '17 at 19:37
Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection like
module.exports = mongoist(connectionString);
. (Read about connectionString
in MongoDB Manual.)– Alexandr Nil
Oct 1 '17 at 19:37
add a comment |
6 Answers
6
active
oldest
votes
up vote
99
down vote
You can create a mongoUtil.js
module that has functions to both connect to mongo and return a mongo db instance:
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db ) {
_db = db;
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
To use it, you would do this in your app.js
:
var mongoUtil = require( 'mongoUtil' );
mongoUtil.connectToServer( function( err ) {
// start the rest of your app here
} );
And then, when you need access to mongo somewhere, you can do this:
var mongoUtil = require( 'mongoUtil' );
var db = mongoUtil.getDb();
db.collection( 'users' ).find();
The reason this works is that in node, when modules are require
'd, they only get loaded/sourced once so you will only ever end up with one instance of _db
and mongoUtil.getDb()
will always return that same instance.
Note, code not tested.
6
Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
– Farhan Ahmad
Feb 9 '15 at 2:59
9
How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
– Ayan
Aug 22 '17 at 12:02
2
I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
– Keming
Jan 17 at 19:44
2
@KemingZeng - you need to make sure that all modules that use mongoUtil are imported inapp.js
within the callback function ofconnectToServer
. If yourequire
them inapp.js
before_db
is set, then you'll get undefined errors in the other modules.
– Mike
Feb 17 at 21:40
2
As of mongoDB version 4 it should bevar database = mongoUtil.getDb(); database.db().collection( 'users' )
.
– Julian Veerkamp
Aug 23 at 12:01
|
show 3 more comments
up vote
9
down vote
If you are using Express, then you can use express-mongo-db module that allows you to get db connection in request object.
Install
npm install --save express-mongo-db
server.js
var app = require('express')();
var expressMongoDb = require('express-mongo-db');
app.use(expressMongoDb('mongodb://localhost/test'));
routes/users.js
app.get('/', function (req, res, next) {
req.db // => Db object
});
add a comment |
up vote
7
down vote
Here's how I do it with contemporary syntax, based on go-oleg's example. Mine is tested and functional.
I put some comments in the code.
./db/mongodb.js
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://user:password@localhost:27017/dbName'
let _db
const connectDB = async (callback) => {
try {
MongoClient.connect(uri, (err, db) => {
_db = db
return callback(err)
})
} catch (e) {
throw e
}
}
const getDB = () => _db
const disconnectDB = () => _db.close()
module.exports = { connectDB, getDB, disconnectDB }
./index.js
// Load MongoDB utils
const MongoDB = require('./db/mongodb')
// Load queries & mutations
const Users = require('./users')
// Improve debugging
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason)
})
const seedUser = {
name: 'Bob Alice',
email: 'test@dev.null',
bonusSetting: true
}
// Connect to MongoDB and put server instantiation code inside
// because we start the connection first
MongoDB.connectDB(async (err) => {
if (err) throw err
// Load db & collections
const db = MongoDB.getDB()
const users = db.collection('users')
try {
// Run some sample operations
// and pass users collection into models
const newUser = await Users.createUser(users, seedUser)
const listUsers = await Users.getUsers(users)
const findUser = await Users.findUserById(users, newUser._id)
console.log('CREATE USER')
console.log(newUser)
console.log('GET ALL USERS')
console.log(listUsers)
console.log('FIND USER')
console.log(findUser)
} catch (e) {
throw e
}
const desired = true
if (desired) {
// Use disconnectDB for clean driver disconnect
MongoDB.disconnectDB()
process.exit(0)
}
// Server code anywhere above here inside connectDB()
})
./users/index.js
const ObjectID = require('mongodb').ObjectID
// Notice how the users collection is passed into the models
const createUser = async (users, user) => {
try {
const results = await users.insertOne(user)
return results.ops[0]
} catch (e) {
throw e
}
}
const getUsers = async (users) => {
try {
const results = await users.find().toArray()
return results
} catch (e) {
throw e
}
}
const findUserById = async (users, id) => {
try {
if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
const results = await users.findOne(ObjectID(id))
return results
} catch (e) {
throw e
}
}
// Export garbage as methods on the Users object
module.exports = { createUser, getUsers, findUserById }
is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
– shanks
May 16 at 21:44
It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
– agm1984
May 17 at 22:08
add a comment |
up vote
5
down vote
go-oleg is basically right, but in these days you (probably) dont want use "mongodb" itself, rather use some framework, which will do a lot of "dirty work" for you.
For example, mongoose is one of the most common. This is what we have in our initial server.js
file :
const mongoose = require('mongoose');
const options = {server: {socketOptions: {keepAlive: 1}}};
mongoose.connect(config.db, options);
This is everything what is needed to set it up. Now use this anywhere in your code
const mongoose = require('mongoose');
And you get that instance you set up with mongoose.connect
1
mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
– Saras Arya
Apr 13 '17 at 14:16
1
Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
– agm1984
Jul 24 '17 at 6:10
add a comment |
up vote
2
down vote
Initialize the connection as a promise:
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://...'
const client = new MongoClient(uri)
const connection = client.connect() // initialized connection
And then call the connection whenever you wish you perform an action on the database:
// if I want to insert into the database...
const connect = connection
connect.then(() => {
const doc = { id: 3 }
const db = client.db('database_name')
const coll = db.collection('collection_name')
coll.insertOne(doc, (err, result) => {
if(err) throw err
})
})
add a comment |
up vote
0
down vote
A tested solution based on the accepted answer:
mongodbutil.js:
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "<connection string>", function( err, client ) {
_db = client.db("<collection name>");
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var mongodbutil = require( './mongodbutil' );
mongodbutil.connectToServer( function( err ) {
//app goes online once this callback occurs
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var companiesRouter = require('./routes/companies');
var activitiesRouter = require('./routes/activities');
var registerRouter = require('./routes/register');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/companies', companiesRouter);
app.use('/activities', activitiesRouter);
app.use('/register', registerRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
//end of calback
});
module.exports = app;
activities.js -- a route:
var express = require('express');
var router = express.Router();
var mongodbutil = require( '../mongodbutil' );
var db = mongodbutil.getDb();
router.get('/', (req, res, next) => {
db.collection('activities').find().toArray((err, results) => {
if (err) return console.log(err)
res.render('activities', {activities: results, title: "Activities"})
});
});
router.post('/', (req, res) => {
db.collection('activities').save(req.body, (err, result) => {
if (err) return console.log(err)
res.redirect('/activities')
})
});
module.exports = router;
add a comment |
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
99
down vote
You can create a mongoUtil.js
module that has functions to both connect to mongo and return a mongo db instance:
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db ) {
_db = db;
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
To use it, you would do this in your app.js
:
var mongoUtil = require( 'mongoUtil' );
mongoUtil.connectToServer( function( err ) {
// start the rest of your app here
} );
And then, when you need access to mongo somewhere, you can do this:
var mongoUtil = require( 'mongoUtil' );
var db = mongoUtil.getDb();
db.collection( 'users' ).find();
The reason this works is that in node, when modules are require
'd, they only get loaded/sourced once so you will only ever end up with one instance of _db
and mongoUtil.getDb()
will always return that same instance.
Note, code not tested.
6
Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
– Farhan Ahmad
Feb 9 '15 at 2:59
9
How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
– Ayan
Aug 22 '17 at 12:02
2
I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
– Keming
Jan 17 at 19:44
2
@KemingZeng - you need to make sure that all modules that use mongoUtil are imported inapp.js
within the callback function ofconnectToServer
. If yourequire
them inapp.js
before_db
is set, then you'll get undefined errors in the other modules.
– Mike
Feb 17 at 21:40
2
As of mongoDB version 4 it should bevar database = mongoUtil.getDb(); database.db().collection( 'users' )
.
– Julian Veerkamp
Aug 23 at 12:01
|
show 3 more comments
up vote
99
down vote
You can create a mongoUtil.js
module that has functions to both connect to mongo and return a mongo db instance:
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db ) {
_db = db;
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
To use it, you would do this in your app.js
:
var mongoUtil = require( 'mongoUtil' );
mongoUtil.connectToServer( function( err ) {
// start the rest of your app here
} );
And then, when you need access to mongo somewhere, you can do this:
var mongoUtil = require( 'mongoUtil' );
var db = mongoUtil.getDb();
db.collection( 'users' ).find();
The reason this works is that in node, when modules are require
'd, they only get loaded/sourced once so you will only ever end up with one instance of _db
and mongoUtil.getDb()
will always return that same instance.
Note, code not tested.
6
Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
– Farhan Ahmad
Feb 9 '15 at 2:59
9
How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
– Ayan
Aug 22 '17 at 12:02
2
I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
– Keming
Jan 17 at 19:44
2
@KemingZeng - you need to make sure that all modules that use mongoUtil are imported inapp.js
within the callback function ofconnectToServer
. If yourequire
them inapp.js
before_db
is set, then you'll get undefined errors in the other modules.
– Mike
Feb 17 at 21:40
2
As of mongoDB version 4 it should bevar database = mongoUtil.getDb(); database.db().collection( 'users' )
.
– Julian Veerkamp
Aug 23 at 12:01
|
show 3 more comments
up vote
99
down vote
up vote
99
down vote
You can create a mongoUtil.js
module that has functions to both connect to mongo and return a mongo db instance:
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db ) {
_db = db;
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
To use it, you would do this in your app.js
:
var mongoUtil = require( 'mongoUtil' );
mongoUtil.connectToServer( function( err ) {
// start the rest of your app here
} );
And then, when you need access to mongo somewhere, you can do this:
var mongoUtil = require( 'mongoUtil' );
var db = mongoUtil.getDb();
db.collection( 'users' ).find();
The reason this works is that in node, when modules are require
'd, they only get loaded/sourced once so you will only ever end up with one instance of _db
and mongoUtil.getDb()
will always return that same instance.
Note, code not tested.
You can create a mongoUtil.js
module that has functions to both connect to mongo and return a mongo db instance:
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db ) {
_db = db;
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
To use it, you would do this in your app.js
:
var mongoUtil = require( 'mongoUtil' );
mongoUtil.connectToServer( function( err ) {
// start the rest of your app here
} );
And then, when you need access to mongo somewhere, you can do this:
var mongoUtil = require( 'mongoUtil' );
var db = mongoUtil.getDb();
db.collection( 'users' ).find();
The reason this works is that in node, when modules are require
'd, they only get loaded/sourced once so you will only ever end up with one instance of _db
and mongoUtil.getDb()
will always return that same instance.
Note, code not tested.
answered Jul 8 '14 at 14:29
go-oleg
14.3k23238
14.3k23238
6
Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
– Farhan Ahmad
Feb 9 '15 at 2:59
9
How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
– Ayan
Aug 22 '17 at 12:02
2
I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
– Keming
Jan 17 at 19:44
2
@KemingZeng - you need to make sure that all modules that use mongoUtil are imported inapp.js
within the callback function ofconnectToServer
. If yourequire
them inapp.js
before_db
is set, then you'll get undefined errors in the other modules.
– Mike
Feb 17 at 21:40
2
As of mongoDB version 4 it should bevar database = mongoUtil.getDb(); database.db().collection( 'users' )
.
– Julian Veerkamp
Aug 23 at 12:01
|
show 3 more comments
6
Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
– Farhan Ahmad
Feb 9 '15 at 2:59
9
How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
– Ayan
Aug 22 '17 at 12:02
2
I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
– Keming
Jan 17 at 19:44
2
@KemingZeng - you need to make sure that all modules that use mongoUtil are imported inapp.js
within the callback function ofconnectToServer
. If yourequire
them inapp.js
before_db
is set, then you'll get undefined errors in the other modules.
– Mike
Feb 17 at 21:40
2
As of mongoDB version 4 it should bevar database = mongoUtil.getDb(); database.db().collection( 'users' )
.
– Julian Veerkamp
Aug 23 at 12:01
6
6
Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
– Farhan Ahmad
Feb 9 '15 at 2:59
Great example! However, I have a question. How would this work when running your app with multiple clusters? Would it spin up another instance of the connection or simply use the existing connection from source?
– Farhan Ahmad
Feb 9 '15 at 2:59
9
9
How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
– Ayan
Aug 22 '17 at 12:02
How would you handle the case when the mongo connection dies in between? All calls to getDb() would fail in that scenario untill the node application is restarted.
– Ayan
Aug 22 '17 at 12:02
2
2
I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
– Keming
Jan 17 at 19:44
I tried this code but I got null when do mongoUtil.getDb(), I don't know why is that.
– Keming
Jan 17 at 19:44
2
2
@KemingZeng - you need to make sure that all modules that use mongoUtil are imported in
app.js
within the callback function of connectToServer
. If you require
them in app.js
before _db
is set, then you'll get undefined errors in the other modules.– Mike
Feb 17 at 21:40
@KemingZeng - you need to make sure that all modules that use mongoUtil are imported in
app.js
within the callback function of connectToServer
. If you require
them in app.js
before _db
is set, then you'll get undefined errors in the other modules.– Mike
Feb 17 at 21:40
2
2
As of mongoDB version 4 it should be
var database = mongoUtil.getDb(); database.db().collection( 'users' )
.– Julian Veerkamp
Aug 23 at 12:01
As of mongoDB version 4 it should be
var database = mongoUtil.getDb(); database.db().collection( 'users' )
.– Julian Veerkamp
Aug 23 at 12:01
|
show 3 more comments
up vote
9
down vote
If you are using Express, then you can use express-mongo-db module that allows you to get db connection in request object.
Install
npm install --save express-mongo-db
server.js
var app = require('express')();
var expressMongoDb = require('express-mongo-db');
app.use(expressMongoDb('mongodb://localhost/test'));
routes/users.js
app.get('/', function (req, res, next) {
req.db // => Db object
});
add a comment |
up vote
9
down vote
If you are using Express, then you can use express-mongo-db module that allows you to get db connection in request object.
Install
npm install --save express-mongo-db
server.js
var app = require('express')();
var expressMongoDb = require('express-mongo-db');
app.use(expressMongoDb('mongodb://localhost/test'));
routes/users.js
app.get('/', function (req, res, next) {
req.db // => Db object
});
add a comment |
up vote
9
down vote
up vote
9
down vote
If you are using Express, then you can use express-mongo-db module that allows you to get db connection in request object.
Install
npm install --save express-mongo-db
server.js
var app = require('express')();
var expressMongoDb = require('express-mongo-db');
app.use(expressMongoDb('mongodb://localhost/test'));
routes/users.js
app.get('/', function (req, res, next) {
req.db // => Db object
});
If you are using Express, then you can use express-mongo-db module that allows you to get db connection in request object.
Install
npm install --save express-mongo-db
server.js
var app = require('express')();
var expressMongoDb = require('express-mongo-db');
app.use(expressMongoDb('mongodb://localhost/test'));
routes/users.js
app.get('/', function (req, res, next) {
req.db // => Db object
});
answered Jun 18 '17 at 6:25
Mukesh Chapagain
17.8k1086104
17.8k1086104
add a comment |
add a comment |
up vote
7
down vote
Here's how I do it with contemporary syntax, based on go-oleg's example. Mine is tested and functional.
I put some comments in the code.
./db/mongodb.js
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://user:password@localhost:27017/dbName'
let _db
const connectDB = async (callback) => {
try {
MongoClient.connect(uri, (err, db) => {
_db = db
return callback(err)
})
} catch (e) {
throw e
}
}
const getDB = () => _db
const disconnectDB = () => _db.close()
module.exports = { connectDB, getDB, disconnectDB }
./index.js
// Load MongoDB utils
const MongoDB = require('./db/mongodb')
// Load queries & mutations
const Users = require('./users')
// Improve debugging
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason)
})
const seedUser = {
name: 'Bob Alice',
email: 'test@dev.null',
bonusSetting: true
}
// Connect to MongoDB and put server instantiation code inside
// because we start the connection first
MongoDB.connectDB(async (err) => {
if (err) throw err
// Load db & collections
const db = MongoDB.getDB()
const users = db.collection('users')
try {
// Run some sample operations
// and pass users collection into models
const newUser = await Users.createUser(users, seedUser)
const listUsers = await Users.getUsers(users)
const findUser = await Users.findUserById(users, newUser._id)
console.log('CREATE USER')
console.log(newUser)
console.log('GET ALL USERS')
console.log(listUsers)
console.log('FIND USER')
console.log(findUser)
} catch (e) {
throw e
}
const desired = true
if (desired) {
// Use disconnectDB for clean driver disconnect
MongoDB.disconnectDB()
process.exit(0)
}
// Server code anywhere above here inside connectDB()
})
./users/index.js
const ObjectID = require('mongodb').ObjectID
// Notice how the users collection is passed into the models
const createUser = async (users, user) => {
try {
const results = await users.insertOne(user)
return results.ops[0]
} catch (e) {
throw e
}
}
const getUsers = async (users) => {
try {
const results = await users.find().toArray()
return results
} catch (e) {
throw e
}
}
const findUserById = async (users, id) => {
try {
if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
const results = await users.findOne(ObjectID(id))
return results
} catch (e) {
throw e
}
}
// Export garbage as methods on the Users object
module.exports = { createUser, getUsers, findUserById }
is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
– shanks
May 16 at 21:44
It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
– agm1984
May 17 at 22:08
add a comment |
up vote
7
down vote
Here's how I do it with contemporary syntax, based on go-oleg's example. Mine is tested and functional.
I put some comments in the code.
./db/mongodb.js
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://user:password@localhost:27017/dbName'
let _db
const connectDB = async (callback) => {
try {
MongoClient.connect(uri, (err, db) => {
_db = db
return callback(err)
})
} catch (e) {
throw e
}
}
const getDB = () => _db
const disconnectDB = () => _db.close()
module.exports = { connectDB, getDB, disconnectDB }
./index.js
// Load MongoDB utils
const MongoDB = require('./db/mongodb')
// Load queries & mutations
const Users = require('./users')
// Improve debugging
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason)
})
const seedUser = {
name: 'Bob Alice',
email: 'test@dev.null',
bonusSetting: true
}
// Connect to MongoDB and put server instantiation code inside
// because we start the connection first
MongoDB.connectDB(async (err) => {
if (err) throw err
// Load db & collections
const db = MongoDB.getDB()
const users = db.collection('users')
try {
// Run some sample operations
// and pass users collection into models
const newUser = await Users.createUser(users, seedUser)
const listUsers = await Users.getUsers(users)
const findUser = await Users.findUserById(users, newUser._id)
console.log('CREATE USER')
console.log(newUser)
console.log('GET ALL USERS')
console.log(listUsers)
console.log('FIND USER')
console.log(findUser)
} catch (e) {
throw e
}
const desired = true
if (desired) {
// Use disconnectDB for clean driver disconnect
MongoDB.disconnectDB()
process.exit(0)
}
// Server code anywhere above here inside connectDB()
})
./users/index.js
const ObjectID = require('mongodb').ObjectID
// Notice how the users collection is passed into the models
const createUser = async (users, user) => {
try {
const results = await users.insertOne(user)
return results.ops[0]
} catch (e) {
throw e
}
}
const getUsers = async (users) => {
try {
const results = await users.find().toArray()
return results
} catch (e) {
throw e
}
}
const findUserById = async (users, id) => {
try {
if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
const results = await users.findOne(ObjectID(id))
return results
} catch (e) {
throw e
}
}
// Export garbage as methods on the Users object
module.exports = { createUser, getUsers, findUserById }
is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
– shanks
May 16 at 21:44
It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
– agm1984
May 17 at 22:08
add a comment |
up vote
7
down vote
up vote
7
down vote
Here's how I do it with contemporary syntax, based on go-oleg's example. Mine is tested and functional.
I put some comments in the code.
./db/mongodb.js
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://user:password@localhost:27017/dbName'
let _db
const connectDB = async (callback) => {
try {
MongoClient.connect(uri, (err, db) => {
_db = db
return callback(err)
})
} catch (e) {
throw e
}
}
const getDB = () => _db
const disconnectDB = () => _db.close()
module.exports = { connectDB, getDB, disconnectDB }
./index.js
// Load MongoDB utils
const MongoDB = require('./db/mongodb')
// Load queries & mutations
const Users = require('./users')
// Improve debugging
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason)
})
const seedUser = {
name: 'Bob Alice',
email: 'test@dev.null',
bonusSetting: true
}
// Connect to MongoDB and put server instantiation code inside
// because we start the connection first
MongoDB.connectDB(async (err) => {
if (err) throw err
// Load db & collections
const db = MongoDB.getDB()
const users = db.collection('users')
try {
// Run some sample operations
// and pass users collection into models
const newUser = await Users.createUser(users, seedUser)
const listUsers = await Users.getUsers(users)
const findUser = await Users.findUserById(users, newUser._id)
console.log('CREATE USER')
console.log(newUser)
console.log('GET ALL USERS')
console.log(listUsers)
console.log('FIND USER')
console.log(findUser)
} catch (e) {
throw e
}
const desired = true
if (desired) {
// Use disconnectDB for clean driver disconnect
MongoDB.disconnectDB()
process.exit(0)
}
// Server code anywhere above here inside connectDB()
})
./users/index.js
const ObjectID = require('mongodb').ObjectID
// Notice how the users collection is passed into the models
const createUser = async (users, user) => {
try {
const results = await users.insertOne(user)
return results.ops[0]
} catch (e) {
throw e
}
}
const getUsers = async (users) => {
try {
const results = await users.find().toArray()
return results
} catch (e) {
throw e
}
}
const findUserById = async (users, id) => {
try {
if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
const results = await users.findOne(ObjectID(id))
return results
} catch (e) {
throw e
}
}
// Export garbage as methods on the Users object
module.exports = { createUser, getUsers, findUserById }
Here's how I do it with contemporary syntax, based on go-oleg's example. Mine is tested and functional.
I put some comments in the code.
./db/mongodb.js
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://user:password@localhost:27017/dbName'
let _db
const connectDB = async (callback) => {
try {
MongoClient.connect(uri, (err, db) => {
_db = db
return callback(err)
})
} catch (e) {
throw e
}
}
const getDB = () => _db
const disconnectDB = () => _db.close()
module.exports = { connectDB, getDB, disconnectDB }
./index.js
// Load MongoDB utils
const MongoDB = require('./db/mongodb')
// Load queries & mutations
const Users = require('./users')
// Improve debugging
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason)
})
const seedUser = {
name: 'Bob Alice',
email: 'test@dev.null',
bonusSetting: true
}
// Connect to MongoDB and put server instantiation code inside
// because we start the connection first
MongoDB.connectDB(async (err) => {
if (err) throw err
// Load db & collections
const db = MongoDB.getDB()
const users = db.collection('users')
try {
// Run some sample operations
// and pass users collection into models
const newUser = await Users.createUser(users, seedUser)
const listUsers = await Users.getUsers(users)
const findUser = await Users.findUserById(users, newUser._id)
console.log('CREATE USER')
console.log(newUser)
console.log('GET ALL USERS')
console.log(listUsers)
console.log('FIND USER')
console.log(findUser)
} catch (e) {
throw e
}
const desired = true
if (desired) {
// Use disconnectDB for clean driver disconnect
MongoDB.disconnectDB()
process.exit(0)
}
// Server code anywhere above here inside connectDB()
})
./users/index.js
const ObjectID = require('mongodb').ObjectID
// Notice how the users collection is passed into the models
const createUser = async (users, user) => {
try {
const results = await users.insertOne(user)
return results.ops[0]
} catch (e) {
throw e
}
}
const getUsers = async (users) => {
try {
const results = await users.find().toArray()
return results
} catch (e) {
throw e
}
}
const findUserById = async (users, id) => {
try {
if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
const results = await users.findOne(ObjectID(id))
return results
} catch (e) {
throw e
}
}
// Export garbage as methods on the Users object
module.exports = { createUser, getUsers, findUserById }
answered Aug 26 '17 at 23:20
agm1984
3,45911733
3,45911733
is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
– shanks
May 16 at 21:44
It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
– agm1984
May 17 at 22:08
add a comment |
is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
– shanks
May 16 at 21:44
It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
– agm1984
May 17 at 22:08
is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
– shanks
May 16 at 21:44
is the try catch in your first snippet necessary? the connect function is an async function. The error is already being caught using the node style callback.
– shanks
May 16 at 21:44
It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
– agm1984
May 17 at 22:08
It's a very observant question that I love. I'm not sure without studying it closer in the habitat you place the code. There will be a limited number of pathways it could take during code execution. I added it mostly to show that you could put a custom handler there and because I default to include try/catch in async functions. It is simply a hook point. Good question though. I will update if you find an additional note.
– agm1984
May 17 at 22:08
add a comment |
up vote
5
down vote
go-oleg is basically right, but in these days you (probably) dont want use "mongodb" itself, rather use some framework, which will do a lot of "dirty work" for you.
For example, mongoose is one of the most common. This is what we have in our initial server.js
file :
const mongoose = require('mongoose');
const options = {server: {socketOptions: {keepAlive: 1}}};
mongoose.connect(config.db, options);
This is everything what is needed to set it up. Now use this anywhere in your code
const mongoose = require('mongoose');
And you get that instance you set up with mongoose.connect
1
mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
– Saras Arya
Apr 13 '17 at 14:16
1
Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
– agm1984
Jul 24 '17 at 6:10
add a comment |
up vote
5
down vote
go-oleg is basically right, but in these days you (probably) dont want use "mongodb" itself, rather use some framework, which will do a lot of "dirty work" for you.
For example, mongoose is one of the most common. This is what we have in our initial server.js
file :
const mongoose = require('mongoose');
const options = {server: {socketOptions: {keepAlive: 1}}};
mongoose.connect(config.db, options);
This is everything what is needed to set it up. Now use this anywhere in your code
const mongoose = require('mongoose');
And you get that instance you set up with mongoose.connect
1
mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
– Saras Arya
Apr 13 '17 at 14:16
1
Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
– agm1984
Jul 24 '17 at 6:10
add a comment |
up vote
5
down vote
up vote
5
down vote
go-oleg is basically right, but in these days you (probably) dont want use "mongodb" itself, rather use some framework, which will do a lot of "dirty work" for you.
For example, mongoose is one of the most common. This is what we have in our initial server.js
file :
const mongoose = require('mongoose');
const options = {server: {socketOptions: {keepAlive: 1}}};
mongoose.connect(config.db, options);
This is everything what is needed to set it up. Now use this anywhere in your code
const mongoose = require('mongoose');
And you get that instance you set up with mongoose.connect
go-oleg is basically right, but in these days you (probably) dont want use "mongodb" itself, rather use some framework, which will do a lot of "dirty work" for you.
For example, mongoose is one of the most common. This is what we have in our initial server.js
file :
const mongoose = require('mongoose');
const options = {server: {socketOptions: {keepAlive: 1}}};
mongoose.connect(config.db, options);
This is everything what is needed to set it up. Now use this anywhere in your code
const mongoose = require('mongoose');
And you get that instance you set up with mongoose.connect
answered Jul 13 '16 at 8:46
libik
12k62859
12k62859
1
mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
– Saras Arya
Apr 13 '17 at 14:16
1
Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
– agm1984
Jul 24 '17 at 6:10
add a comment |
1
mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
– Saras Arya
Apr 13 '17 at 14:16
1
Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
– agm1984
Jul 24 '17 at 6:10
1
1
mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
– Saras Arya
Apr 13 '17 at 14:16
mongoose is an ORM. Read this to know about possible pitfalls for the same. No doubt ORM's are great when used for developmental and learning process but not for production. Just keep this in mind
– Saras Arya
Apr 13 '17 at 14:16
1
1
Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
– agm1984
Jul 24 '17 at 6:10
Mongoose also requires schemas. I am using MongoDB package as part of polyglot persistence with Neo4j, so it's nice to define document properties as needed.
– agm1984
Jul 24 '17 at 6:10
add a comment |
up vote
2
down vote
Initialize the connection as a promise:
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://...'
const client = new MongoClient(uri)
const connection = client.connect() // initialized connection
And then call the connection whenever you wish you perform an action on the database:
// if I want to insert into the database...
const connect = connection
connect.then(() => {
const doc = { id: 3 }
const db = client.db('database_name')
const coll = db.collection('collection_name')
coll.insertOne(doc, (err, result) => {
if(err) throw err
})
})
add a comment |
up vote
2
down vote
Initialize the connection as a promise:
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://...'
const client = new MongoClient(uri)
const connection = client.connect() // initialized connection
And then call the connection whenever you wish you perform an action on the database:
// if I want to insert into the database...
const connect = connection
connect.then(() => {
const doc = { id: 3 }
const db = client.db('database_name')
const coll = db.collection('collection_name')
coll.insertOne(doc, (err, result) => {
if(err) throw err
})
})
add a comment |
up vote
2
down vote
up vote
2
down vote
Initialize the connection as a promise:
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://...'
const client = new MongoClient(uri)
const connection = client.connect() // initialized connection
And then call the connection whenever you wish you perform an action on the database:
// if I want to insert into the database...
const connect = connection
connect.then(() => {
const doc = { id: 3 }
const db = client.db('database_name')
const coll = db.collection('collection_name')
coll.insertOne(doc, (err, result) => {
if(err) throw err
})
})
Initialize the connection as a promise:
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://...'
const client = new MongoClient(uri)
const connection = client.connect() // initialized connection
And then call the connection whenever you wish you perform an action on the database:
// if I want to insert into the database...
const connect = connection
connect.then(() => {
const doc = { id: 3 }
const db = client.db('database_name')
const coll = db.collection('collection_name')
coll.insertOne(doc, (err, result) => {
if(err) throw err
})
})
edited Oct 13 at 17:01
answered Oct 13 at 7:54
Henry Bothin
315
315
add a comment |
add a comment |
up vote
0
down vote
A tested solution based on the accepted answer:
mongodbutil.js:
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "<connection string>", function( err, client ) {
_db = client.db("<collection name>");
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var mongodbutil = require( './mongodbutil' );
mongodbutil.connectToServer( function( err ) {
//app goes online once this callback occurs
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var companiesRouter = require('./routes/companies');
var activitiesRouter = require('./routes/activities');
var registerRouter = require('./routes/register');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/companies', companiesRouter);
app.use('/activities', activitiesRouter);
app.use('/register', registerRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
//end of calback
});
module.exports = app;
activities.js -- a route:
var express = require('express');
var router = express.Router();
var mongodbutil = require( '../mongodbutil' );
var db = mongodbutil.getDb();
router.get('/', (req, res, next) => {
db.collection('activities').find().toArray((err, results) => {
if (err) return console.log(err)
res.render('activities', {activities: results, title: "Activities"})
});
});
router.post('/', (req, res) => {
db.collection('activities').save(req.body, (err, result) => {
if (err) return console.log(err)
res.redirect('/activities')
})
});
module.exports = router;
add a comment |
up vote
0
down vote
A tested solution based on the accepted answer:
mongodbutil.js:
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "<connection string>", function( err, client ) {
_db = client.db("<collection name>");
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var mongodbutil = require( './mongodbutil' );
mongodbutil.connectToServer( function( err ) {
//app goes online once this callback occurs
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var companiesRouter = require('./routes/companies');
var activitiesRouter = require('./routes/activities');
var registerRouter = require('./routes/register');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/companies', companiesRouter);
app.use('/activities', activitiesRouter);
app.use('/register', registerRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
//end of calback
});
module.exports = app;
activities.js -- a route:
var express = require('express');
var router = express.Router();
var mongodbutil = require( '../mongodbutil' );
var db = mongodbutil.getDb();
router.get('/', (req, res, next) => {
db.collection('activities').find().toArray((err, results) => {
if (err) return console.log(err)
res.render('activities', {activities: results, title: "Activities"})
});
});
router.post('/', (req, res) => {
db.collection('activities').save(req.body, (err, result) => {
if (err) return console.log(err)
res.redirect('/activities')
})
});
module.exports = router;
add a comment |
up vote
0
down vote
up vote
0
down vote
A tested solution based on the accepted answer:
mongodbutil.js:
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "<connection string>", function( err, client ) {
_db = client.db("<collection name>");
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var mongodbutil = require( './mongodbutil' );
mongodbutil.connectToServer( function( err ) {
//app goes online once this callback occurs
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var companiesRouter = require('./routes/companies');
var activitiesRouter = require('./routes/activities');
var registerRouter = require('./routes/register');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/companies', companiesRouter);
app.use('/activities', activitiesRouter);
app.use('/register', registerRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
//end of calback
});
module.exports = app;
activities.js -- a route:
var express = require('express');
var router = express.Router();
var mongodbutil = require( '../mongodbutil' );
var db = mongodbutil.getDb();
router.get('/', (req, res, next) => {
db.collection('activities').find().toArray((err, results) => {
if (err) return console.log(err)
res.render('activities', {activities: results, title: "Activities"})
});
});
router.post('/', (req, res) => {
db.collection('activities').save(req.body, (err, result) => {
if (err) return console.log(err)
res.redirect('/activities')
})
});
module.exports = router;
A tested solution based on the accepted answer:
mongodbutil.js:
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "<connection string>", function( err, client ) {
_db = client.db("<collection name>");
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var mongodbutil = require( './mongodbutil' );
mongodbutil.connectToServer( function( err ) {
//app goes online once this callback occurs
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var companiesRouter = require('./routes/companies');
var activitiesRouter = require('./routes/activities');
var registerRouter = require('./routes/register');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/companies', companiesRouter);
app.use('/activities', activitiesRouter);
app.use('/register', registerRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
//end of calback
});
module.exports = app;
activities.js -- a route:
var express = require('express');
var router = express.Router();
var mongodbutil = require( '../mongodbutil' );
var db = mongodbutil.getDb();
router.get('/', (req, res, next) => {
db.collection('activities').find().toArray((err, results) => {
if (err) return console.log(err)
res.render('activities', {activities: results, title: "Activities"})
});
});
router.post('/', (req, res) => {
db.collection('activities').save(req.body, (err, result) => {
if (err) return console.log(err)
res.redirect('/activities')
})
});
module.exports = router;
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "<connection string>", function( err, client ) {
_db = client.db("<collection name>");
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
var MongoClient = require( 'mongodb' ).MongoClient;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( "<connection string>", function( err, client ) {
_db = client.db("<collection name>");
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var mongodbutil = require( './mongodbutil' );
mongodbutil.connectToServer( function( err ) {
//app goes online once this callback occurs
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var companiesRouter = require('./routes/companies');
var activitiesRouter = require('./routes/activities');
var registerRouter = require('./routes/register');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/companies', companiesRouter);
app.use('/activities', activitiesRouter);
app.use('/register', registerRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
//end of calback
});
module.exports = app;
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var mongodbutil = require( './mongodbutil' );
mongodbutil.connectToServer( function( err ) {
//app goes online once this callback occurs
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var companiesRouter = require('./routes/companies');
var activitiesRouter = require('./routes/activities');
var registerRouter = require('./routes/register');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/companies', companiesRouter);
app.use('/activities', activitiesRouter);
app.use('/register', registerRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
//end of calback
});
module.exports = app;
var express = require('express');
var router = express.Router();
var mongodbutil = require( '../mongodbutil' );
var db = mongodbutil.getDb();
router.get('/', (req, res, next) => {
db.collection('activities').find().toArray((err, results) => {
if (err) return console.log(err)
res.render('activities', {activities: results, title: "Activities"})
});
});
router.post('/', (req, res) => {
db.collection('activities').save(req.body, (err, result) => {
if (err) return console.log(err)
res.redirect('/activities')
})
});
module.exports = router;
var express = require('express');
var router = express.Router();
var mongodbutil = require( '../mongodbutil' );
var db = mongodbutil.getDb();
router.get('/', (req, res, next) => {
db.collection('activities').find().toArray((err, results) => {
if (err) return console.log(err)
res.render('activities', {activities: results, title: "Activities"})
});
});
router.post('/', (req, res) => {
db.collection('activities').save(req.body, (err, result) => {
if (err) return console.log(err)
res.redirect('/activities')
})
});
module.exports = router;
answered May 30 at 10:49
steve
664
664
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24621940%2fhow-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
The same kind of question I asked a couple of days ago. stackoverflow.com/questions/24547357/…
– Salvador Dali
Jul 8 '14 at 1:22
Check mongoist driver. It is "built with async/await in mind" and allows lazily export connection like
module.exports = mongoist(connectionString);
. (Read aboutconnectionString
in MongoDB Manual.)– Alexandr Nil
Oct 1 '17 at 19:37