0

At the moment, I develop a node.js REST webservice with express. I used MongoDB + Mongoose to establish a database. Now, I have the problem, that I can only use the db connection in the file where I established the connection. I found a solution to use the connection also in other files by "module.exports" the _db variable. But I don't know, if this is the best practise. Here is my code:

databaseManager.js

// Establish a connection to the database.
mongoose.Promise = global.Promise
mongoose.connect('mongodb://'+cfg.db.ip+':'+cfg.db.port+'/'+cfg.db.name)
var _db = mongoose.connection
_db.on('error', console.error.bind(console, 'DB connection error'))
_db.once('open', function() 
{
    console.log("DatabaseM: Connected to the database")
})
[...]
module.exports =
{
    db     :   _db,
}

otherFile.js

var database = require('./databaseManagement')
[...]
database.db.collection('users').findOne({ name: "ashton"}, function(err, user)
{
   if (err) return callback(consts.ERROR_DB, null)
   if (!user) return callback(consts.WARN_DB_NO_CLIENT)

   callback(null, user)
})

It works great. But there may be a risk that I do not see? Thanks a lot :-)

2
  • You don't need to export mongoose connection at all. You should only work with models which have access to connection through mongoose internally, you don't need to care about it. Simply create model var Users = mongoose.model('user', UserSchema); and use it like this Users.find(....); Commented Oct 5, 2016 at 14:16
  • It's like magic. Nice :-) Commented Oct 5, 2016 at 17:35

1 Answer 1

1

In your app.js file :

var url="mongdb:\\localhost:27017\dbname";
mongoose.connect(url); //it open default connection for mongodb and is handled by mongoose

Now perform all your task whatever you want :

mongoose.connection.on('connected', function () { console.log('Mongoose default connection open to ' + dbURI); });

Bring all your database model in app.js file like as such:

var model1 = require('./models/model1');

model1.js

var mongoose = require('mongoose');
var data = new mongoose.Schema({
    name:{type:String, required:true}
});
module.exports = mongoose.model('collectionName', data);

Now, when all your tasks are over. Simply close default connection like this :

mongoose.connection.on('disconnected', function () { 
    console.log('Mongoose default connection disconnected'); 
});

If any error occurs in connection handle it like this :

mongoose.connection.on('error',function (err) { 
    console.log('Mongoose default connection error: ' + err);
});

If node service exits then close connection usig this code

process.on('SIGINT', function() { 
    mongoose.connection.close(function () { 
        console.log('Mongoose default connection disconnected through app termination'); 
        process.exit(0); 
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your quick response. That means that I have to open the connection and close it again for each database call in each file?
Why I should import all my models into app.js? I want call the database from another file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.