[英]Error then connecting nodemon server with MongoDB
我試圖將我的節點服務器與我的 MongoDB 數據庫連接起來,但我一直遇到這個錯誤,我對節點和 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});
})();
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.