Nicholas Mordecai
Nicholas Mordecai

Reputation: 889

Node.js run MongoDB from within application

I am building a component that is consumable by NPM. The application needs to connect to the database. If the user does not specify the details to the database uri in the config files, my application should spin up an instance of mongoDB from within the application itself.

I have seen many tutorials on how to integrate mongoDB into node.js, express, mocha and many other libraries, but all connect to an external database that's already running.

mongoDB server is being included as part of the dependencies so is installed with everything else, but I'm coming up short on material online on how to do boot up the database when the application starts.

Any help would be greatly appreciated. I suspect the information is out there, but I'm having a hard time finding it :(

Upvotes: 2

Views: 5441

Answers (2)

levilime
levilime

Reputation: 362

You can look into starting a subprocess. So letting Node run mongo as an external program. This way you could create a new mongodb instance for any user that fits that criteria. You can use for example the node "child process" library and use the spawn function to 'spawn' a new database instance by writing there the console command as already stated by Larry Turtis or here mongodb - multiple instances. It could look like this, to start the instance:

const spawn = require('child_process').spawn;
const pipe = spawn('mongod', ['--dbpath=<LOCATION>', '--port', '<PORT>'])

You can pipe console output to node with this:

    pipe.stdout.on('data', function (data) {
        printback(data.toString('utf8'));
    });

    pipe.stderr.on('data', (data) => {
        printback(data.toString('utf8'));
    });

    pipe.on('close', (code) => {
        callback('Process exited with code: '+ code);
    });

And kill the mongodb running instance by keeping the pipe reference and then doing this:

static end_pipe(pipe) {
    pipe.kill('SIGINT');
}

Upvotes: 3

Larry Turtis
Larry Turtis

Reputation: 1916

The command to boot mongoDB is available on the NPM mongodb page. Adding --fork and --logpath because I assume you want it to start in the background.

mongod --dbpath=/data --port 27017 --fork --logpath /var/log/mongod.log

You could just include this as part of your npm start script in package.json:

"scripts": {"start": "mongod --dbpath=/data --port 27017 --fork --logpath /var/log/mongod.log"}

Upvotes: 2

Related Questions