Connecting to MongoDB with Mongoose

The mongoose.connect() function is the easiest way to connect to MongoDB using Mongoose. Once you've connected, you can then create a Mongoose model and start interacting with MongoDB.

await mongoose.connect( 'mongodb://localhost:27017/test' , { useNewUrlParser : true }); const userSchema = new mongoose.Schema({ name : String }); const UserModel = mongoose.model( 'User' , userSchema); await UserModel.create({ name : 'test' });

The mongoose.connect() function returns a promise that fulfills if Mongoose successfully connects to MongoDB, or rejects if Mongoose could not connect.

const options = { useNewUrlParser : true }; const err = await mongoose.connect( 'mongodb://nota.domain:27017/test' , options). catch( err => err); err.message;

Many older tutorials recommend listening to connection events. This isn't strictly necessary because Mongoose handles automatically reconnecting on its own if it loses connectivity to MongoDB after initial connection.

The promise mongoose.connect() returns only rejects if there is an error when Mongoose is initially connecting to MongoDB. Once Mongoose successfully connects, it automatically handles reconnecting if it loses connectivity.

The reconnectFailed Event

Mongoose handles automatically reconnecting to MongoDB. Internally, the underlying MongoDB driver tries to reconnect reconnectTries times every reconnectInterval milliseconds if you're connected to a single server. You can set reconnectTries and reconnectInterval in the mongoose.connect() options.

mongoose.connect( 'mongodb://localhost:27017/test' , { useNewUrlParser : true , reconnectTries: 60 , reconnectInterval : 2000 })

When Mongoose gives up, it emits a 'reconnectFailed' event on the connection.

mongoose.connection.on( 'reconnectFailed' , () => { process.nextTick( () => { throw new Error ( 'Mongoose could not reconnect to MongoDB server' ); }); });

If you're connected to a replica set, reconnectTries and reconnectInterval don't do anything. Mongoose will continue to reconnect indefinitely if it loses connectivity to a replica set after initial connection.

More Mongoose Tutorials