我正在使用 nodeJs + MongoDB 开发一个小项目(REST API)。我已经能够在本地安装 MongoDB 并使用 mongoose 连接到它。但是由于某种原因,当我尝试使用 MongoDB Atlas 进行连接时,它失败了。看起来它已连接,但 2 秒后,我收到一条错误消息,提示套接字已关闭(请参阅下面的错误)。我不知道发生了什么。我已将我的 IP 列入白名单,检查了我的登录信息以确保我使用了正确的密码,并且确实我正在使用,因为我能够使用 MongoDB 指南针进行连接。任何帮助是极大的赞赏。
My current local ENV package versions are:
nodeJs:V9.7.1
mongoose:V6.1
=== MongoDb Atlas ===
mongodb:3.6
下面是我用来连接数据库的代码:
var express = require('express'),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
user = require('./api/models/userModel'),
config = require('./api/config');
bodyParser = require('body-parser');
var authRoutes = require('./api/routes/authRoutes'),
userRoutes = require('./api/routes/userRoutes'),
reviewRoutes = require('./api/routes/reviewRoutes');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://user:myPass@cluster0-shard-00-00 zd6jq.mongodb.net/myDb');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//Swagger Info
var options = {
explorer : true
};
app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
//END Swagger Info
//REGISTER ROUTES
userRoutes(app);
authRoutes(app);
reviewRoutes(app);
app.listen(port);
console.log('iReview RESTful API server listenning on port: ' + port);
module.exports = app;
====错误信息===
/Users/mdiez/node_test/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
^
MongoError: server cluster0-shard-00-00-zd6jq.mongodb.net:27017 sockets closed
at Pool.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/topologies/server.js:325:47)
at Object.onceWrapper (events.js:219:13)
at Pool.emit (events.js:127:13)
at Connection.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/connection/pool.js:101:12)
at Object.onceWrapper (events.js:219:13)
at Connection.emit (events.js:127:13)
at Socket.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/connection/connection.js:142:12)
at Object.onceWrapper (events.js:219:13)
at Socket.emit (events.js:127:13)
at TCP._handle.close [as _onclose] (net.js:558:12)