我正在使用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..."); });
解决方法
您可以尝试以下模式:
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);