0

I have deployed my nodejs project to Heroku and have used the mongodb cluster url but I also want to work in my local machine and use the local host.

I tried writing this code for when it doesn't connect to the cluster it should connect to the local host but the problem is the atlas url doesn't return 'undefined' when not connected.So how to connect with both the atlas cluster and the local host.

var mongoose = require('mongoose');

mongoose.Promise = global.Promise;

require('dotenv').config();

const mlabDB = `mongodb+srv://${process.env.MLAB_USERNAME}:${process.env.MLAB_PASSWORD}@todo-app-qhj7g.mongodb.net/test?retryWrites=true&w=majority`;

mongoose.connect(mlabDB || 'mongodb://localhost:27017/TodoApp', {useNewUrlParser: true})
  .catch((e) => {
    console.log(e);
  });

module.exports = {mongoose};
Bosco
  • 1,536
  • 2
  • 13
  • 25

2 Answers2

0

Have you tried connecting them seperately? As I understand you want to connect them both at the same time. Try this:

mongoose.connect(mlabDB , {useNewUrlParser: true})
  .catch((e) => {
    console.log(e);
  });

After you do everything needed with atlas do everthing again for your own database. Yes you have to connect them seperately and process.

mongoose.connect('mongodb://localhost:27017/TodoApp' , {useNewUrlParser: true})
      .catch((e) => {
        console.log(e);
      });

If you want to connect your own database if atlas connection is not possible. Use console.log to see what atlas returns if connection is not happened. And add an if statement to check if connection is happened or not.

burakarslan
  • 245
  • 2
  • 11
0

Within the code, there is a line:

mlabDB || 'mongodb://localhost:27017/TodoApp'

The variable mlabDB is not returning undefined, because you are defining mlabDB as:

const mlabDB = `mongodb+srv://${process.env.MLAB_USERNAME}...

In this case, if process.env.MLAB_USERNAME is undefined, the string will return:

mongodb+srv://undefined

In answer to your question: "how do I connect with both the atlas cluster and the local host?": use a JavaScript Ternary Operator:

const mlabDB = process.env.MLAB_USERNAME ? `mongodb+srv://${process.env.MLAB_USERNAME}:${process.env.MLAB_PASSWORD}@todo-app-qhj7g.mongodb.net/test?retryWrites=true&w=majority` : ``;

For more info on Heroku Config Vars, see here.

For local vars management, use npm's dotenv package.