我无法让它发挥作用。我打开了mongo和mongod,这是我在git Bash或cmd中编写“node server.js”时得到的结果:
Running on server27017
Not connected to database MongoNetworkError: connection 0 to localhost:27017
closed
这是我的代码。
var express = require('express');
var app = express();
var port = 27017;
//Route
app.get('/', function (req, res) {
res.send('Hello world!');
});
const mongoose = require('mongoose');
const option = {
socketTimeoutMS: 30000,
keepAlive: true,
reconnectTries: 30000
};
mongoose.connect('mongodb://localhost:27017/database1', option).then(function(){
//connected successfully
console.log('Successfully connected to database');
}, function(err) {
//err handle
console.log('Not connected to database ' + err);
});
//Listen to port
app.listen(port, function(){
console.log('Running on server' + port);
});
当我在浏览器中写“http://localhost:27017/database1”时,我得到“看起来你正试图通过本机驱动程序端口上的HTTP访问MongoDB。”
答案 0 :(得分:2)
Express端口不应该是与mongoose相同的端口
答案 1 :(得分:2)
如果您要连接到mlab,则此错误是因为您必须添加系统IP地址。
您可以在“网络访问”标签中添加系统的IP地址