简体   繁体   中英

Searching for best practice to use one mongodb connection in multiple javascript-files

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 :-)

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); 
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM