如何使用猫鼬将后端Node.js连接到MongoDB Atlas?

时间:2019-02-21 15:04:17

标签: node.js mongodb mongoose

我正在尝试连接到cloud.mongodb.com。但是运行时出现错误。

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

但是我遇到错误:

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)]: {} }

这是我安装的软件包:

已安装软件包:

  • [x]表达
  • [x]摩根
  • [x]猫鼬
  • [x]正文解析器
  • [x] cors
  • [x] nodemon
  • [x]和尚(数据库)

1 个答案:

答案 0 :(得分:0)

从服务器上检查IP白名单或防火墙。

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