我正在写一个简单的帖子。我的代码如下:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://node:node@novus.modulusmongo.net:27017/Iganiq8o');
router.use(function(req, res, next) {
console.log('Something is happening.');
next();
});enter code here
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
var Bear = require('./app/models/bears');
router.route('/bears')
.post(function(req, res) {
var bear = new Bear();
bear.name = req.body.name;
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
我之前收到了以下错误
failed to connect to [novus.modulusmongo.net:27017]
我通过更新mongoose纠正了,但现在我仍然得到另一个错误:
/node_modules/mongoose/node_modules/mongodb/lib/server.js:242
process.nextTick(function() { throw err; })
^
错误:连接ETIMEDOUT 54.209.84.209:27017
答案 0 :(得分:0)
尝试使用以下示例
var mg= require('mongoose');
var db = mg.connection;
mg.connect('mongodb://node:node@novus.modulusmongo.net:27017/Iganiq8o');
db.on('open', function (ref) {
console.log('open connection to mongo server.');
});
db.on('connected', function (ref) {
console.log('Connected connection to mongo server.');
});
db.on('disconnected', function (ref) {
console.log(ref);
console.log('disconnected connection.');
});
db.on('close', function (ref) {
console.log('close connection.');
});
db.on('error', function (ref) {
console.log(ref);
console.log('Error connection.');
});
db.on('reconnected', function () {
console.log('MongoDB reconnected!');
});
以下是我得到的错误。
{ MongoError: failed to connect to server [novus.modulusmongo.net:27017] on first connect
at Pool.<anonymous> (E:\v2.4.1\node_modules\mongoose\node_modules\mongodb-core\lib\topologies\server.js:313:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (E:\v2.4.1\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:260:12)
at Connection.g (events.js:291:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket.<anonymous> (E:\v2.4.1\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:162:49)
at Socket.g (events.js:291:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1278:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
name: 'MongoError',
message: 'failed to connect to server [novus.modulusmongo.net:27017] on first connect' }
所以我觉得它本质上只是连接字符串或端口或用户名或密码不正确。尝试通过简单地更改连接字符串,端口,用户名或密码来连接上面的代码。
请记住,27017不是托管服务器上专门的默认端口
尝试使用mlab并查看是否将其免费连接进行测试并在此处获取您的连接字符串https://mlab.com/以查看您的所有代码是否完美运行
希望能帮到你