1

I have 3 different databases set up for testing, development and production.

Now I would like my express app to switch between these databases depending on which script I run.

These are my current scripts:
 "scripts": {
    "start": "NODE_ENV=dev && node index.js",
    "test": "mocha --timeout 10000"
  }

I am assigning the process.env.NODE_ENV value at the top of the test script like this, and the test script runs fine against the correct DB:

process.env.NODE_ENV = 'test';

But when I run npm start, node does not seem to get the value. For instance on this code:

// DB connection

let db;
if (process.env.NODE_ENV == 'test') {
  mongoose.connect(config.DB.test, options);
  db = mongoose.connection;
} else if (process.env.NODE_ENV == 'dev') {
  mongoose.connect(config.DB.dev, options);
  db = mongoose.connection;
  app.use(morgan('combined'));
} else if (process.env.NODE_ENV == 'prod') {
  mongoose.connect(config.DB.prod, options);
  db = mongoose.connection;
  app.use(morgan('combined'));
}

db.on('error', console.error.bind(console, 'connection error:'));

I get the Cannot read property 'on' of undefined error (while running the same code with the test script connects to the correct DB).

What am I doing wrong?

1 Answer 1

3

Try to use this instead:

"start": "NODE_ENV=dev node index.js",

Remove the &&

And I'd like to add a way to handle the env not set too:

var env = process.env.NODE_ENV || 'dev'

Then change every refers to process.env.NODE_ENV to env

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.