Connecting to MongoDB with Mongoose

Aug 1, 2019

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.

// Connect to a MongoDB server running on 'localhost:27017' and use the
// 'test' database.
await mongoose.connect('mongodb://localhost:27017/test', {
  useNewUrlParser: true // Boilerplate for Mongoose 5.x
});

// Once you're connected to MongoDB, you can create a user model and
// use it to save a user to the database.
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 };
// Try to connect to `nota.domain`, which should fail
const err = await mongoose.connect('mongodb://nota.domain:27017/test', options).
  catch(err => err);
// 'failed to connect to server [nota.domain:27017] on first connect'
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, // Boilerplate
  // If you lose connectivity, try reconnecting every 2 seconds. After 60
  // attempts, give up and emit 'reconnectFailed'.
  reconnectTries: 60,
  reconnectInterval: 2000
})

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

// If Mongoose gave up trying to reconnect, kill the process.
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.


Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need to know to build production-ready full-stack apps with Node.js and MongoDB in a few days. Get your copy!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Mongoose Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!