Posts

Showing posts from August, 2019

Stop using the mongoose's default connection

Image
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) { /* ... */ }); 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