}
按照官网的做法下来,还是会出现上述异常的!!!
官方的API都不对,那才折磨人呢!!幸亏,只是玩儿,慢慢搞吧。
看看官方的解释:http://support.cloudfoundry.com/entries/24374128-Mongodb-Migration-URL-must-be-in-the-format-mongodb-user-pass-host-port-dbname
Hi, apologies for this, we are currently working on bringing the documentation up to date. It's clear that the cf-autoconfig module is not working as it should.
看到这句话,不知道同学们有何感想~
其实这里已经解释的很清楚了,我再说说我解决的过程
1. 首先声明,require('mongodb').open、close的数据库连接方式,cf是不支持的,并且官方已经不支持了,参照https://github.com/mongodb/node-mongodb-native
2.数据库连接的推荐方式:
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { if(err) throw err;
var collection = db.collection('test_insert');
collection.insert({a:2}, function(err, docs) {
collection.count(function(err, count) {
console.log(format("count = %s", count));
});
// Locate all the entries using find
collection.find().toArray(function(err, results) {
console.dir(results);
// Let's close the db
db.close();
});
});
})
3. cf中mongodb服务的url:
var svcs = JSON.parse(process.env.VCAP_SERVICES);
var mongourl = svcs['mongolab-n/a'][0].credentials.uri;
4. 所以,我们用127.0.0.1/db是不能连接数据库的,这也是报错的原因。所以把把URL改为
if(process.env.VCAP_SERVICES){ //app is running in the cloud
var svcs = JSON.parse(process.env.VCAP_SERVICES);
mongourl = svcs['mongolab-n/a'][0].credentials.uri;
}else{
//running locally or not on cloud foundry
mongourl = "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db;