当我尝试使用Node JS进行连接时,我收到此错误。我的设置如下:
我的服务器.js
// set up ======================================================================
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var server = require('http').Server(app);
var mongoose = require('mongoose'); // mongoose for mongodb
var port = process.env.PORT || 8000; // set the port
var database = require('./config/database'); // load the database config
var morgan = require('morgan');
var methodOverride = require('method-override');
var io = require('socket.io')(server);
var messageId = {};
// configuration ===============================================================
//mongoose.connect(database.localUrl); // Connect to local MongoDB instance. A remoteUrl is also available (modulus.io)
//app.use(express.static('./public')); // set the static files location /public/img will be /img for users
//app.use(morgan('dev')); // log every request to the console
//app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
//app.use(bodyParser.json()); // parse application/json
//app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
//app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
// Connect to Mongo DB
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
mongoose.connect(database.remoteUrl)
mongoose.connection.on('error', function(e) {
console.log('Could not connect to the database. Exiting now...',e);
process.exit();
});
mongoose.connection.once('open', function() {
console.log("Successfully connected to the database");
})
io.set('origins', '*:*');
http = require('http'),
server = http.createServer(function (req, res) {
//res.writeHead(200,{'content-type':'text/plain'});
// res.write("Sever On");
// res.end();
}),
io = io.listen(server);
io.on('connection', function (socket) {
console.log('User Connected -- Server Online');
socket.on('message', function (msg,msgId) {
io.emit('message', "Hello");
console.log("message from client:", msg);
setInterval(function(){
io.emit("messageStatus",msgId);
},500)
});
});
// app.get('/', function (req, res) {
// res.send('hello world')
// })
server.listen(port);
console.log("App listening on port " + port);
这是我的database.js
module.exports = {
remoteUrl : 'mongodb://username:password@mysystem@ec2-22-22-22.ap-south-1.compute.amazonaws.com:27017/testdb'
};
我通过使用以下命令检查我的Mongo DB是否正在运行:
sudo /opt/bitnami/ctlscript.sh status mongodb
它说 mongodb已经在运行
如果我做错了,请告诉我,我是MongoDB和Node JS的新手。