简体   繁体   中英

Cannot connect atlas with nodejs

This is my server.js file

const express = require('express');
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 }
);
const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})



app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});

.env file

ATLAS_URI=mongodb+srv://nitin:password@data.ztmkm.mongodb.net/test?retryWrites=true&w=majority

I am getting this error

(node:16036) UnhandledPromiseRejectionWarning: Error: queryTxt ETIMEOUT data.ztmkm.mongodb.net at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) (Use node --trace-warnings... to show where the warning was created) (node:16036) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode ). (rejection id: 1) (node:16036) [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.

mongoose.connect() method will throw a promise after successfully connecting to your db and you didn't write a code to recive the promise so instead of this

mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})

use this

const connect=mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });
connect.then((db)=>
{
  console.log("connected correctly to the server")
},(err)=>
{
  console.log(err)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM