Dimitto Dimitto - 4 months ago 27
Node.js Question

Starting up MongoDB through Node.js and then connecting

I'd like to start the MongoDB through Node.js to save myself the trouble of having to do it manually each time, however I'm uncertain what the best method to use is, or for that matter, how to incorporate it, and therefore the dilemma.

I believe the reason that this code is not working (ECONNREFUSED) is that the mongod.exe is not given enough time to start up. If true, what would be the best method to around this? Some sort of loop? Checking the status of the DB somehow? Some sort of synchronous timer?

Ideally, the server should check first if the MongoDB is already running before attempting to start it up, and if it fails to start up and connect after so many attempts to do something else. This sounds like a good plan to me but unforunately I do not know where to start.

I'm really new to coding, and I'm perhaps a little too ambitious with my goals... if I'm doing anything wrong, please kindly let me know.

const express = require('express');
const bodyParser= require('body-parser');
const app = express();
const MongoClient = require('mongodb').MongoClient
const execFile = require('child_process').execFile;

app.use(bodyParser.urlencoded({extended: true}))

var db

execFile("C:/Program Files/MongoDB/Server/3.2/bin/mongod.exe", ['--version'], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);

});

MongoClient.connect('mongodb://localhost:27017/db', (err, database) => {
if (err) return console.log(err)
db = database
app.listen(3000, function() {
console.log('listening on 3000')
})
})

Answer

You could wait till mongodb will start, then connect. Here is the example

  execFile("C:/Program Files/MongoDB/Server/3.2/bin/mongod.exe",  ['--version'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);

  MongoClient.connect('mongodb://localhost:27017/db', (err, database) => {

   if (err) return console.log(err)
   db = database
   app.listen(3000, function() {
     console.log('listening on 3000')
    })
  })

 });

Also in your example you start mongod with --version parameter, and presumably your intention is to start the db itself, correct? So just drop --version parameter.

Comments