본문 바로가기

express

Divide DB by the 'env'

Divide Database by the environment

Situation:

I want to use another DB for TDD. Using just one DB for any enviroment is not that good.
because anyone or any team mates can delete or edit datas without discussion.

Before check enviroment status, We need to know how the environment managed.

Node.js allow us to check what is the environment is now.

How? with this.

process.env.NODE_ENV

And also we can change (or set) "NODE_ENV" if we want.

set NODE_ENV=test
or
set NODE_ENV=dev
or
set NODE_ENV=production

I usually set "NODE_ENV" in the package.json file like this.

// package.json
"scripts": {
    "test": "set NODE_ENV=test && mocha -timeout 100000",
    "build": "set NODE_ENV=production && node index.js",
    "deb": "set NODE_ENV=dev && nodemon index.js"
}

// usually set NODE_ENV before start scripts !

How we can divide the DB?

1. Get ready two DB. One for 'dev', and another for 'test'.

//config.env
MONGODB_URI_FOR_TEST= {uri}
MONGODB_URI_FOR_DEV= {uri}

2. Set environment before connect DB

// package.json
"scripts": {
    "test": "set NODE_ENV=test && mocha -timeout 100000",
    "build": "set NODE_ENV=production && node index.js",
    "deb": "set NODE_ENV=dev && nodemon index.js"
}

// usually set NODE_ENV before start scripts !

3. And Check what environment is it now before connect DB.

//db.js
const mongoose = require('mongoose');

const connectDB = async () => {

    let uri;

    // ! CHECK NODE_ENV HERE
    if (process.env.NODE_ENV.trim() == 'dev') {             
        uri = process.env.MONGODB_URI_DEV;
    } else if (process.env.NODE_ENV.trim() == 'test') {     
        uri = process.env.MONGODB_URI_TEST;
    }

    const conn = await mongoose.connect(uri, {   // ! PASS THE CHOOSED URI HERE.
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false,
        useUnifiedTopology: true
    });

    console.log(`MongoDB Connected: ${conn.connection.host}`);
}

module.exports = connectDB;