连接nodemon服务器与MongoDB时出错



我试图将我的节点服务器与我的MongoDB数据库连接起来,但我一直遇到此错误,我对node和mongodb非常陌生,我尝试将useUnifiedTopology:true放入我的mongo构造函数中?我不确定我在哪里搞砸了。

const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true,useUnifiedTopology: true}
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
// const exercisesRouter = require('./routes/exercises');
// const usersRouter = require('./routes/users');
// app.use('/exercises', exercisesRouter);
// app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
}); ```


```Server is running on port: 5000
(node:21667) UnhandledPromiseRejectionWarning: MongoNetworkError: connection 0 to cluster0-shard-00-00-rsjfl.gcp.mongodb.net:27017 closed
at TLSSocket.<anonymous> (/Users/MYNAME/Desktop/ExcersizeTracker/mern-excersize/backend/node_modules/mongodb/lib/core/connection/connection.js:352:9)
at Object.onceWrapper (events.js:284:20)
at TLSSocket.emit (events.js:196:13)
at net.js:586:12
at TCP.done (_tls_wrap.js:466:7)
(node:21667) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:21667) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code```

这是官方文档中的连接指南:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});

连接方法是异步的。您必须等待完成才能继续。

...
(async () => {
await mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true});
})();
...

最新更新