site icon

Hi, I’m Chris

I am a web developer teaching
regular people how to code

~ Welcome to my blog ~

How to connect Mongo Atlas Database to a Keystone CMS project

Mongo Atlas is a convenient way to set up a mongoDB database, and we connect it to our applications using a connection string. When using the Keystone 5 CMS for the first time, there is no obvious place to add this connection string.

Keystone's index.js entry point imports the Mongoose adapter, then sets up a new Keystone instance:

const { MongooseAdapter: Adapter } = require('@keystonejs/adapter-mongoose');

const PROJECT_NAME = "My Keystone project";


const keystone = new Keystone({
  name: PROJECT_NAME,
  adapter: new Adapter(),
  onConnect: initialiseData,
});


If we try to run the dev server without connecting a database, we may see a message like this "Error: connect ECONNREFUSED...."

It may not be obvious where we add our Atlas database connection string to begin, but we need to pass it to the new Adaptor.

If we head over to the database adaptor docs, we see that the adaptor can take in an options object, with a mongoUri property:

Mongoose Adaptor Options

Here we can pass in our connection string (from Mongo Atlas) directly like this:

const keystone = new Keystone({
  name: PROJECT_NAME,
  adapter: new Adapter({ mongoUri: "mongodb+srv://yourConnectionString..." }),
  onConnect: initialiseData,
});

Or, better still, add it in as an environment variable.

  1. Install the dotenv package

    # with npm 
    npm install dotenv
     
    # or with Yarn 
    yarn add dotenv
    
  2. Create a new file called .env in the projects root, and set up the variable using any of the environment variables from the docs (MONGO_URI, DATABASE_URL etc), like this:

    // .env
    MONGO_URI=mongodb+srv://yourConnectionString...
    
  3. Require the package (as early as possible in your app, such as index.js):

    require('dotenv').config()
    
  4. Replace the connection string with the environment variable:

    const keystone = new Keystone({
      name: PROJECT_NAME,
      adapter: new Adapter({ mongoUri: process.env.MONGO_URI }),
      onConnect: initialiseData,
    });
    

Finally, don't forget to add the .env file to your .gitignore.

And now you should be able to get going with Mongo Atlas and Keystone CMS by starting the dev server.


- By Chris Dixon

Chris Dixon is a web developer and teacher. Teaching thousands of students mainly in Vue.js React.js, WordPress and web development.