好吧,我是一个 Node/MongoDB 新手,我目前正在学习本教程:http://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html .
这是我迄今为止的代码
var MongoClient = require('mongoDB').MongoClient;
MongoClient.connect("mongodb://localhost:8888/exampleDb", function(err, db){
if( !err ){
console.log("We are connected");
} else console.log(err);
});
但是,当我运行 node/node/index.js 时,我的控制台会记录:
[Error: connection closed]
我尝试禁用防火墙并添加 auto-reconnect: true,但这两种方法都不起作用。我在网上似乎找不到问题,可能是哪里出了问题?
编辑:这就是我设置服务器的方式
var server = require("./server");
var router = require("./router");
// in router.js
function route(handle, pathname, response){
console.log("About to route a request for "+pathname);
if( typeof handle[pathname] === "function"){
handle[pathname](response);
} else {
console.log("404");
response.writeHead(404, {"Content-Type":"text/plain"});
response.write("404 not found");
response.end();
}
}
exports.route = route;
// in server.js
var http = require("http");
var url = require("url");
function start(route, handle){
function onRequest(request, response){
var pathname = url.parse(request.url).pathname;
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
}
exports.start = start;
server.start(router.route, handle);
最佳答案
好吧,你的错误很简单。默认情况下,mongoDB 在端口 27017 运行,在您的代码中,您尝试连接 8888 端口上的 mongod 实例。此端口用于您的 Node 项目,而不是 MongoDB。
首先,您应该启动 mongod 实例。如果你使用的是 Ubuntu,你可以从这里开始:
sudo service mongodb start
如果您在另一个平台中,并且 mongodb 路径在您的 PATH 环境中,您可以使用以下命令简单地启动它:
mongod
通过以下方式更改连接 URI:
var MongoClient = require('mongoDB').MongoClient;
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db){
if( !err ){
console.log("We are connected");
} else console.log(err);
});
关于node.js - 错误: Connection Closed - MongoDB Node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23127933/