连接数据库采用的下面的代码 修改Models/index的 连接代码
var mongoose = require('mongoose');
var db = exports.Db = mongoose.createConnection();
var options = {
db: { native_parser: false}, //bae提示设置成false才能运行
server: { poolSize: 5 },
user: '',
pass: ''
}
var isDev = false;
var host = isDev ? 'localhost' : 'mongo.duapp.com';
var port = isDev ? '27017' : '8908';
var database = isDev ? 'foo' : 'bae mongdb database';
var user = isDev ? 'foo' : 'bae api key';
var pass = isDev ? 'bar' : 'bae api secret';
db.open(host, database, port, options);
db.on('error', function (err) {
//logger.error("connect error :" + err);
//监听BAE mongodb异常后关闭闲置连接
db.close();
});
//监听db close event并重新连接
db.on('close', function () {
logger.info("connect close retry connect ");
db.open(host, database, port, options);
});
修改app.js mongoStore
app.use(session({
secret: config.session_secret,
key: 'sid',
store: new MongoStore({
db: "xPHzywbdmuggRjmPKD",
host: 'mongo.duapp.com',
port: 8908,
username:'hKi429544=hlR8xFLyQW',
password:'H44Ud8zZ8gr==mPMIMUQeHgI'
}),
resave: true,
saveUninitialized: true
}));
修改完成上传Bae可以运行,之后不超过一分钟显示“no open connections” 是数据库连接都关闭了?
@lzxue 当时好像可以连接上,但是session好像不行,有点烦了就没继续研究了,后来写了简单连接mongodb的例子可以连上,你参考一下 var http = require(‘http’); var mongoose = require(‘mongoose’); var port = 18080; var username = "HahMqSkZWUq9QWHsWceXmG"; var password = "XH82hOf5MGzoMUMUkCNj0KdBvecF"; var address = "mongo.duapp.com"; var database = "pQPzvWlctdHpUjrbtFnX"; http.createServer(function(req, res) { mongoose.connect("mongodb://"+username+":"+password+"@"+address+":8908/"+database); var db = mongoose.connection; // db.on(‘error’,console.error.bind(console,’connection error’)); db.on('error’, function(){ res.writeHead(200, {’Content-Type’: 'text/html’}); res.write(‘nodejs’); res.end(‘connect mongodb error’); }); db.once('open’,function callback(){ res.writeHead(200, {’Content-Type’: 'text/html’}); res.write(‘Node.js’); res.end(‘success connected to mongodb’); }); }).listen(port);
@lzxue mongodb存储session的问题我也解决了,不过连接mongodb还有点问题 mongodb重连 附带session的解决办法: app.js中使用session: app.use(session({ secret:settings.cookieSecret, store: new MongoStore({ url:"mongodb://"+settings.uid+":"+settings.pwd+"@"+settings.host+":"+settings.port+"/"+settings.db})})); settings.js内容如下: module.exports = { cookieSecret: 'node-demo’, db: 'hiuhi’, port: '8908’, uid: 'kljdfgodioihj’, pwd: 'kldfjdioo’, host: ‘mongo.duapp.com’ };