然后将nodemon服务器与MongoDB连接出错

问题描述 投票:0回答:1

我试图将节点服务器与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```
javascript node.js database mongodb mongoose
1个回答
0
投票
这里是官方文档的连接指南:

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(); });

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.