DEV Community 👩‍💻👨‍💻

Han Mai
Han Mai

Posted on

Stop using the mongoose's default connection

Look at the below typical example of mongoose use.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});
var MyModel = mongoose.model('Test', new Schema({ name: String }));
// Works
MyModel.findOne(function(error, result) { /* ... */ });
Enter fullscreen mode Exit fullscreen mode

What if we want to make another connections? Or if we want to connect to another database? We can't use mongoose.connect() again, mongoose won't know which one we want to interact with. And don't ever think of creating different modules where separated mongoose objects are created and used because require() doesn't work that way, mongoose object is cached for the first time it is imported.

The connection object is used to create and retrieve models. Models are always scoped to a single connection. Please be aware that mongoose creates a default connection when we call mongoose.connect(). We can access the default connection using mongoose.connection.

Not everybody notices that. So my suggestion is that we avoid using mongoose.connect(). Instead of that, we use mongoose.createConnection(). By this way, we can save much time for other developers who will maintain and extend the project in the future. We implicitly ask them to aware the fact of mongoose's default connection.

The above example may be re-written as the following.

const mongoose = require('mongoose');
var connection = mongoose.createConnection('mongodb://localhost:27017/myapp',
                                           {useNewUrlParser: true});
var MyModel = connection.model('Test', new Schema({ name: String }));
// Works
MyModel.findOne(function(error, result) { /* ... */ });
Enter fullscreen mode Exit fullscreen mode

Reference API: https://mongoosejs.com/docs/connections.html
** This post is copy from my personal blog https://rainforest01.blogspot.com/2019/08/stop-using-mongooses-default-connection.html

Top comments (1)

Collapse
 
sibelius profile image
Sibelius Seraphini

dx is worse this way

Want to rep DEV and be comfy at the same time?

Check out our classic DEV shirt — available in multiple colors.