← Back to all tutorials

Creating a Database on mLab

Set up a MongoDB database using a cloud service — create a database, add a user, and get the connection string for your app.

Creating a Database on mLab

You need a database to store users who log in via Google. MongoDB is an excellent choice for this — it stores data as JSON-like documents that map naturally to JavaScript objects. We will use a cloud-hosted MongoDB service.

Setting Up MongoDB Atlas

  1. Go to mongodb.com/atlas (mLab has been merged into MongoDB Atlas)
  2. Create a free account
  3. Create a new Cluster (the free tier is fine)
  4. Click Database Access → Add a database user with a username and password
  5. Click Network Access → Allow access from anywhere (for development)
  6. Click Connect → Choose Connect your application
  7. Copy the connection string

The Connection String

mongodb+srv://username:password@cluster0.xxxxx.mongodb.net/oauth-app?retryWrites=true

Replace username, password, and oauth-app with your actual credentials and database name.

Installing Mongoose

npm install mongoose

Connecting in app.js

// app.js
const mongoose = require('mongoose');
const keys = require('./config/keys');

// Connect to MongoDB
mongoose.connect(keys.mongodb.dbURI, function() {
    console.log('Connected to MongoDB');
});

// Then start listening
app.listen(3000, function() {
    console.log('App listening on port 3000');
});

Storing the URI Securely

// config/keys.js
module.exports = {
    google: {
        clientID: '...',
        clientSecret: '...'
    },
    mongodb: {
        dbURI: 'mongodb+srv://username:password@cluster0.xxxxx.mongodb.net/oauth-app'
    },
    session: {
        cookieKey: 'random_secret_string'
    }
};

Key Takeaways

  • MongoDB Atlas (formerly mLab) provides free cloud-hosted MongoDB databases
  • Install mongoose to connect and interact with MongoDB from Node.js
  • Store the connection string in your keys file — never commit it to Git
  • Call mongoose.connect() before starting the server