4

I am building a node application using express and node-postgres (https://github.com/brianc/node-postgres). I only want to build the db client connection once, and I'd like to be able to access this db connection from different modules. What is the best way to do this? I'm trying to only export the db connection, not the whole express app. Essentially, what's the best way to export and access objects across a node application?

I've checked out this similar question, but it seems specific to mongoose.

Best way to share database connection param with mongoose/node.js

Community
  • 1
  • 1
user2253099
  • 43
  • 1
  • 3

3 Answers3

5

There's not a thing called "the best way". If you need to use the same object among different modules you have to wrap it in a module. Something like this:

//db.js
var postgres = require (...)
var connection;

module.exports = {
  getConnection: function (){
    return connection;
  },
  createConnection: function (){
    connection = createConnection (postgress);
  }
};

//app.js - main file
require ("./db").createConnection ();

//a.js
var db = require("./db")
db.getConnection()

//b.js
var db = require("./db")
db.getConnection()
Gabriel Llamas
  • 18,244
  • 26
  • 87
  • 112
0

HI Im working on a solution for this got it from RefLink

You might create a scheme like this to map your data

    const User = mongoose.model('Story', userSchema);
    module.exports = User;
    const mongoose = require('mongoose');
    let Schema = mongoose.Schema;
    const userSchema = new Schema({
    UserID: {
        type: mongoose.Schema.Types.Mixed,
    },
    User_Info: {
        First_Name: {
        type: String,
        },
        Last_Name: {
        type: String,
        },
        Current_Address: {
        type: String,
        },
        Email_Address: {
        type: String,
        },
    },
        Phone_Numbers: [{
            Home_Phone: {
            type: Number,
            },
            Work_Phone: {
            type: Number,
            },
            Cell_Phone: {
            type: Number,
            },
                Phone_verified: [{
                Home: Boolean,
                Work: Boolean,
                Cell: Boolean,
                }],
        }],
    })
    const User = mongoose.model('User', userSchema);
    module.exports = User;

ANd the API route might look like this

        app.post('/api/user', function(req, res) {
    User.create({
        UserID: req.body.userid,
        User_Info: req.body.userinfo,
        First_Name: req.body.firstname,
        Last_Name: req.body.lastname,
        Current_Address: req.body.currentaddress,
        Email_Address: req.body.emailaddress,
        Phone_Numbers: req.body.phonenumbers,
        Home_Phone: req.body.homephone,
        Work_Phone: req.body.workphone,
        Cell_Phone: req.body.cellphone,
        Phone_Verified:
        req.body.phoneverified,
        Home: req.body.home,
        Work: req.body.work,
        Cell: req.body.cell,
    }).then(user => {
        res.json(user)
    });
    });
Cesar Vega
  • 455
  • 6
  • 15
-1

You can do something like that..

//db.js
var pg = require('pg'); 

var conString = "tcp://postgres:1234@localhost/postgres";

module.exports.connectDatabase = function(callback){
var client = new pg.Client(conString);
client.connect(function(err) {
  if(err){
     console.log(err);
     process.exit(1);
  }

  module.exports.client = client;
  callback();
})

//app.js
// We are trying to connect to database at the start of our app and if it fails we exit       the process
var db = require('./db');
db.connectDatabase(function(){
  // your other code
})

//a.js
var db = require('./db');
//you can access your client here to perform database operations like that
db.client
khurrum qureshi
  • 933
  • 1
  • 8
  • 13