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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With