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
- Go to
mongodb.com/atlas(mLab has been merged into MongoDB Atlas) - Create a free account
- Create a new Cluster (the free tier is fine)
- Click Database Access → Add a database user with a username and password
- Click Network Access → Allow access from anywhere (for development)
- Click Connect → Choose Connect your application
- 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
mongooseto 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