Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose OpenShift Connection

I'm building an application on openShift using nodejs and mongodb. I'm also using mongoose and try to connect with this code

var url = process.env.OPENSHIFT_MONGODB_DB_URL;
    var db = mongoose.connect(
        url,
        function(err) {
            console.log("Error loading the db...");
        });

Checking on the openshift logs I can see that it gives me the error message. What's the right way to do this?

like image 442
Manuel Castro Avatar asked Mar 16 '15 09:03

Manuel Castro


1 Answers

You could try the following pattern:

server.js

// call the packages we need
var express    = require('express');        
var app        = express();                 
var mongoose   = require('mongoose');

var url = '127.0.0.1:27017/' + process.env.OPENSHIFT_APP_NAME;

// if OPENSHIFT env variables are present, use the available connection info:
if (process.env.OPENSHIFT_MONGODB_DB_URL) {
    url = process.env.OPENSHIFT_MONGODB_DB_URL +
    process.env.OPENSHIFT_APP_NAME;
}

// Connect to mongodb
var connect = function () {
    mongoose.connect(url);
};
connect();

var db = mongoose.connection;

db.on('error', function(error){
    console.log("Error loading the db - "+ error);
});

db.on('disconnected', connect);
like image 94
chridam Avatar answered Oct 25 '22 23:10

chridam