我的问题是关于mongo没有连接到服务器? 为什么说首次连接时无法连接到服务器[localhost:27017] [MongoError:connect ECONNREFU SED 127.0.0.1:27017]
Here is my code:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/BlogApp");
app.set("views engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function (req, res) {
res.send('Hello World!')
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
答案 0 :(得分:0)
在您的计算机上安装mongodb,(如果您使用的是Mac,请运行brew install mongodb
),然后打开一个新终端,然后运行mongod
,然后重新启动您的应用
答案 1 :(得分:0)
mongod
或sudo mongod
然后,您需要通过添加以下代码来验证是否成功连接或是否发生连接错误。
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('We are connected to db!');
});
您的完整服务器代码应如下所示。
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
// Use native promises
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/BlogApp");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
console.log('We are connected to db!');
});
app.set("views engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function (req, res) {
res.send('Hello World!')
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
答案 2 :(得分:0)