Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of starting mongodb and express?

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?

Edit:

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).

like image 995
WhatisSober Avatar asked Oct 24 '15 09:10

WhatisSober


2 Answers

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!

like image 70
Peter Avatar answered Sep 28 '22 09:09

Peter


In your package.json you can defined scripts. Here is a list of reserved commands can be found here: https://docs.npmjs.com/misc/scripts

If you are on a based OS unix you can do something like this:

"scripts": {
    "prestart": "mongod --dbpath data --config mongo.conf &",
    "start": "node server.js",
    "poststart": "kill %%",
}

Then when you want to run this from the terminal just do npm start

The & at the end of the prestart command means run in background and the kill %% in the poststart command kills the most resent background task (you can also do %1 for the first background task). This might break if you have other background tasks going so be aware of that.

Also if you are hosting MongoDB on another server for production but locally for development you can use:

"scripts": {
    "start": "node server.js",
    "predev": "mongod --dbpath data --config mongo.conf &",
    "dev": "node server.js",
    "postdev": "kill %%",
}

Then when you want to do development you can use npm dev and when you are in production you can use npm start.

Also keep in mind when you are setting up your MongoClient to specify useNewUrlParser: true and useUnifiedTopology: true in the options argument for MongoClient.connect(url, opts) because mongoDB has a small startup time and more likely then not your node script is going to have a smaller startup time then your database and will through an error saying your database was not found.

like image 35
Leyla Becker Avatar answered Sep 28 '22 09:09

Leyla Becker