Mongoose OpenShift连接

时间:2015-03-16 09:45:13

标签: node.js mongodb mongoose openshift

我正在使用nodejs和mongodb在openShift上构建应用程序。我也在使用mongoose并尝试连接此代码

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

检查openshift日志我可以看到它给出了错误消息。什么是正确的方法?

1 个答案:

答案 0 :(得分:9)

您可以尝试以下模式:

<强> 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);