Where to make mongoose connection / any database connection Where to make mongoose connection / any database connection mongodb mongodb

Where to make mongoose connection / any database connection


You could make a mongoose.js file like so:

const mongoose = require('mongoose');mongoose.Promise = global.Promise;mongoose.connect(process.env.MONGODB_URI, {useMongoClient: true});module.exports = {mongoose};

Which you then require in your mongoose model files like so:

const mongoose = require('mongoose');

That way you only write the connection code once, and are able to import it to wherever you see fit.


I don't use Mongoose, but I think it's a bad idea that every time you create a new model or a instance, a new database connection will be created. There should be only one database connection for each request, and they could be recycled to the pool and wait for the next request. Meaning no matter how many models you have, they should share the same connection to the database. I think connections are still precious with MongoDB. Hope this suggestion will help you a little.