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.