如何在Cloud9中连接MongoDB?

我有一个在Cloud9连接数据库MongoDB的问题请帮忙解决这个问题!

var MongoClient = require("mongodb").MongoClient; var port = process.env.PORT; var ip = process.env.IP; MongoClient.connect("mongodb://"+ip+":"+port+"/test",function(error,db){ if(!error){ console.log("We are connected"); } else{ console.dir(error); //failed to connect to [127.4.68.129:8080] } }); 

输出:

 Running Node Process Your code is running at 'http://demo-project.alfared1991.c9.io'. Important: use 'process.env.PORT' as the port and 'process.env.IP' as the host in your scripts! [Error: failed to connect to [127.4.68.129:8080]] 

process.env.PORTprocess.env.IP是应用程序的端口和IP地址,而不是数据库。 你需要从你的MongoDB提供者中取出你的Mongo连接string。

下面是来自Node.js主页的hello world示例,修改为使用两个环境variables。

 var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(process.env.PORT || 1337, process.env.IP || '127.0.0.1'); 

如果你按照https://docs.c9.io/setting_up_mongodb.html这个链接,你将在你的工作区下设置并运行你的mongodb守护进程。

如果你看看./mongod的输出,你会发现这个输出:

 2015-08-22T12:46:47.120+0000 [initandlisten] MongoDB starting : pid=7699 port=27017 dbpath=data 64-bit host=velvetdeth-express-example-1804858 

只需将主机和端口值复制到您的mongodbconfiguration,设置数据库url,在这种情况下是:

 mongodb://velvetdeth-express-example-1804858:27017 

对于遇到此问题的其他人,解决方法如下: https : //docs.c9.io/setting_up_mongodb.html

MongoDB预装在Cloud9工作区中。 运行这个:

 $ mkdir data $ echo 'mongod --bind_ip=$IP --dbpath=data --nojournal --rest "$@"' > mongod $ chmod a+x mongod 

要启动Mongodb进程,请运行:

 $ ./mongod 

然后“运行”你的node.js应用程序脚本,你就可以参加比赛了。

以下是参数的含义:

–dbpath = data(因为它默认是不可访问的/ var / db)

–nojournal,因为mongodb通常预先分配2 GB的日志文件(超过Cloud9磁盘空间配额)

–bind_ip = $ IP(因为你不能绑定到0.0.0.0)

–rest运行在默认端口28017上