Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I put database connection information in a Node.js app?

Node.js is my first backend language and I am at the point where I am asking myself "where do I put the database connection information?".

There is a lot of good information regarding this issue. Unfortunately for me all the examples are in PHP. I get the ideas but I am not confident enough to replicate it in Node.js.

In PHP you would put the information in a config file outside the web root, and include it when you need database data.

How would you do this in Node.js? using the Express.js framework.

So far I have this:

var express = require('express'), app = express();
var mysql = require('mysql');

app.get('/', function(req,res) {

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'store'
});

var query = connection.query('SELECT * from customers where email = "[email protected]"');

query.on('error', function(err) {

    throw err;

});

query.on('fields', function(fields) {

    console.log('this is fields');

});

query.on('result', function(row) {

    var first = row.first_name;
    var last = row.last_name;

    res.render('index.jade', {
        title: "My first name is " + first,
        category: "My last name is " + last
    });


    });

});

app.listen(80, function() {
    console.log('we are logged in');
});

As you can see I have a basic express application with 1 GET route. This route sets off the function to go to the database and pull out information based on an email address.

At the top of the GET route is the database connection information. Where do I put that? How do I call it? How do I keep it out of web root, and include it like PHP ? Can you please show me in a working example. Thanks!

like image 704
user3658794 Avatar asked Nov 19 '14 20:11

user3658794


People also ask

CAN node JS Access database?

Node. js supports all kinds of databases no matter if it is a relational database or NoSQL database. However, NoSQL databases like MongoDb are the best fit with Node. js.


1 Answers

I use the Express Middleware concept for same and that gives me nice flexibility to manage files.

I am writing a detailed answer, which includes how i am use the config params in app.js to connect to DB.

So my app structure looks something this: enter image description here

How i connect to DB? (I am using MongoDB, mongoose is ORM, npm install mongoose)

var config = require('./config/config');
var mongoose = require("mongoose");

var connect = function(){
var options = {
  server: {
     socketOptions:{
        keepAlive : 1
     }
  }
};
mongoose.connect(config.db,options);
};
connect();

under the config folder i also have 'env' folder, which stores the environment related configurations in separate files such as development.js, test.js, production.js

Now as the name suggests, development.js stores the configuration params related to my development environment and same applies to the case of test and production. Now if you wish you can have some more configuration setting such as 'staging' etc.

project-name/config/config.js

var path = require("path");
var extend = require("util")._extend;

var development = require("./env/development");
var test = require("./env/test");
var production = require("./env/production");

var defaults = {
   root: path.normalize(__dirname + '/..')
};

module.exports = {
   development: extend(development,defaults),
   test: extend(test,defaults),
   production: extend(production,defaults)
}[process.env.NODE_ENV || "development"]

project-name/config/env/test.js

module.exports = {
   db: 'mongodb://localhost/mongoExpress_test'
};

Now you can make it even more descriptive by breaking the URL's into, username, password, port, database, hostname.

For For more details have a look at my repo, where you can find this implementation, in fact now in all of my projects i use the same configuration.

If you are more interested then have a look at Mean.js and Mean.io, they have some better ways to manage all such things. If you are beginner i would recommend to keep it simple and get things going, once you are comfortable, you can perform magic on your own. Cheers

like image 104
NarendraSoni Avatar answered Sep 27 '22 17:09

NarendraSoni