Home » Nodejs » Correct way of starting mongodb and express?

Correct way of starting mongodb and express?

Posted by: admin November 30, 2017 Leave a comment


I have an app which runs on express and communicates with mongodb. This is how I start my app:

1.Start Mongodb

mongod --dbpath data --config mongo.conf"

2.Start Express

node server.js

My question is, Is there a way to combine these? I know node is single threaded so we cant run both express and mongo from server.js but what is the correct way? Is it possible to start mongo from a javascript file using npm?


I can run mongod –dbpath data and node server.js separately on two different command prompt. My question is to start them from one file (if possible).


start creates new cmd in windows
here is my config:

"scripts": {
  "prestart": "start mongod --config ./data/mongod.cfg",
  "start": "node ./server/bin/www",
  "poststart": "start mongo admin --eval \"db.getSiblingDB('admin').shutdownServer()\"",
  "pretest": "start mongod --dbpath data",
  "test": "mocha test",
  "posttest": "start mongo admin --eval \"db.getSiblingDB('admin').shutdownServer()\""

Good luck!


If you are running on Linux you could use the package.json file to define scripts which do just what you need.

There are a few issues altho :

If you are running Linux you could use

"mongod --fork --dbpath data --config mongo.conf" and "node index.js" to use mongodb and run the app at the same time and that would work just fine.

But if you are on windows you have to use a separate console window for mongo and a separate one for the app.

If you are running on Windows I would probably use my package.json scripts to run mongodb and I would run my app in another terminal since it’s easier to type node index.js than the mongod part.


Set-up mongo to run as a windows service, I always have mongo on and it has worked for the last 3 years on my dev machine. On deployment machine set mongo up to be controlled by a daemon.


Yes. Using your package.json you can define scripts:

  "name": "my package",
  "version": "1.0.0",
  "scripts": {
    "start": "mongod --dbpath data --config mongo.conf && node server.js",
  "devDependencies": {
    "express": "*"

Calling npm start will execute your start script defined in the package.json

For more see https://docs.npmjs.com/misc/scripts