Heroku上的Node.js Express App不会使用Mongoose连接到MongoLab数据库

我试图让我的node.js快速应用程序连接到使用Mongoose的Heroku上的MongoLab数据库。 我已经使用app.configureproduction中将我的数据库URI设置为我的MongoLab URI,正如您在Heroku日志中所看到的,它肯定dbURI设置为MongoLab URI。 我已经确定了我的NODE_ENV production 。 我的问题是什么?

app.js

 var express = require('express'); var mongoose = require('mongoose') , dbURI = 'localhost'; var app = express(); app.configure('production', function () { console.log("production!"); dbURI = 'mongodb://brad.ross.35:Brad1234@ds031347.mongolab.com:31347/heroku_app6861425'; console.log(dbURI); }); mongoose.connect(dbURI, 'test'); mongoose.connection.on('error', console.error.bind(console, 'connection error:')); var postSchema = new mongoose.Schema({ body: String }); var Post = mongoose.model('Post', postSchema); app.configure(function () { //app.use(express.logger()); app.use(express.bodyParser()); app.use(express.static(__dirname + '/static')); }); app.set('views', __dirname + '/views'); app.set('view engine','jade'); app.get('/', function(request, response) { response.render('index'); }); app.post('/result', function(request, response) { var post = new Post({body: request.body.text}); post.save(function (err) { if (err) { console.log("error!"); } else { console.log("saved!"); } }); Post.find(function (err, posts) { if (!err) { console.log("found!"); console.log(posts); response.render('result', {posts: posts}); } else { console.log("error!"); response.render('result', {posts: []}); } }); }); app.get('/result', function (request, response) { Post.find(function (err, posts) { if (!err) { console.log("found!"); console.log(posts); response.render('result', {posts: posts}); } else { console.log("error!"); response.render('result', {posts: []}); } }); }); app.listen(process.env.PORT || 5000); 

Heroku日志

 2012-08-21T16:52:21+00:00 heroku[web.1]: State changed from crashed to starting 2012-08-21T16:52:22+00:00 heroku[slugc]: Slug compilation finished 2012-08-21T16:52:23+00:00 heroku[web.1]: Starting process with command `node app.js` 2012-08-21T16:52:24+00:00 app[web.1]: production! 2012-08-21T16:52:24+00:00 app[web.1]: mongodb://brad.ross.35:PASSWORD@ds031347.mongolab.com:31347/heroku_app6861425 2012-08-21T16:52:24+00:00 app[web.1]: connection error: [Error: failed to connect to [ds031347.mongolab.com:31347/heroku_app6861425:27017]] 2012-08-21T16:52:25+00:00 heroku[web.1]: State changed from starting to up 

当传递URI时,不需要单独传递数据库名称(这会混淆mongoose)。

做就是了

 var uri = 'mongodb://brad.ross.35:Brad1234@ds031347.mongolab.com:31347/heroku_app6861425' mongoose.connect(uri) 

使用testing分贝,改变你的URI:

 var uri = 'mongodb://brad.ross.35:Brad1234@ds031347.mongolab.com:31347/test' 

我没有和Mongoose一起工作,但是当我和MongoLab在过去有连接问题时,是由于连接到假设连接的数据库和客户端代码导致的竞争条件。 通常情况下,解决scheme是绑定到open事件,或者提供一个callback,在恢复启动需要连接之前由底层驱动程序调用。 这是我用Mongoskin做的,我从来没有问题。

麦克