简体   繁体   中英

How to connect backend nodejs to mongodb atlas using mongoose?

I'm trying to connect to cloud.mongodb.com. but when runing i getting an error.

const express = require('express');
const cors = require('cors');
const bodyParser = require("body-parser");
const logger = require('morgan');
const Data =  require("./data");
const mongoose = require("mongoose");


const API_PORT = 5000;

/// database config
const DB_KEY = "mongodb+srv://twituet:<mypassWord>@cluster0-ziifr.mongodb.net/test?retryWrites=true";

mongoose
  .connect(
    DB_KEY, {useNewUrlParser: true}
  )
  .then(() => {
    console.log("Connected to database!");
  })
  .catch((error) => {
    console.log("Connection failed!");
    console.log(error);
  });

but I'm getting error:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\think>cd C:\Users\think\Documents\Coding\ReactApp\twituet\server

C:\Users\think\Documents\Coding\ReactApp\twituet\server>npm run dev

> server@1.0.0 dev C:\Users\think\Documents\Coding\ReactApp\twituet\server
> nodemon index.js

[nodemon] 1.18.10
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
listent http://localhost:5000
Connection failed!
{ MongoNetworkError: connection 4 to cluster0-shard-00-00-ziifr.mongodb.net:2701
7 closed
    at TLSSocket.<anonymous> (C:\Users\think\Documents\Coding\ReactApp\twituet\s
erver\node_modules\mongodb-core\lib\connection\connection.js:276:9)
    at Object.onceWrapper (events.js:277:13)
    at TLSSocket.emit (events.js:194:15)
    at _handle.close (net.js:600:12)
    at TCP.done (_tls_wrap.js:388:7)
  name: 'MongoNetworkError',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: {} }

here is my package installed:

Package installed:

  • [x] express
  • [x] morgan
  • [x] mongoose
  • [x] body-parser
  • [x] cors
  • [x] nodemon
  • [x] monk (database)

check IP whitelist or firewall from your server.

https://github.com/Automattic/mongoose/issues/5237

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