简体   繁体   English

如何使用MongoDB Atlas连接MongoDB

[英]How to connect MongoDB using MongoDB Atlas

I have created MongoDB Atlas account, and tried to connect. 我已经创建了MongoDB Atlas帐户,并尝试进行连接。 But got the error below. 但是出现下面的错误。

MongoDB connection error MongoNetworkError: failed to connect to server [cluster0-shard-00-00-c487z.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to cluster0-shard-00-00-c487z.mongodb.net:27017 closed .......] MongoDB连接错误MongoNetworkError:首次连接[MongoNetworkError:到cluster0-shard-00-00-c487z.mongodb.net的连接5时,无法连接到服务器[cluster0-shard-00-00-c487z.mongodb.net:27017]。 27017关闭.......]

Here is my code. 这是我的代码。

const mongoose = require('mongoose');
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const Data = require('./data');
const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();
const dbRoute = 'mongodb+srv://<username>:<Password>@cluster0-c487z.mongodb.net/fullstack_app';
mongoose.connect(dbRoute, {useNewUrlParser: true});
let db = mongoose.connection;
db.once('open', () => console.log('connected to the database'));
db.on('error', console.log.bind(console, 'MongoDB connection error'));
router.post('/putData', (req, res) => {
    let data = new Data();
    const { id, message } = req.body;
    if ((!id && id !== 0) || !message) {
      return res.json({
        success: false,
        error: 'INVALID INPUTS',
      });
    }
    data.message = message;
    data.id = id;
    data.save((err) => {
      if (err) return res.json({ success: false, error: err });
      return res.json({ success: true });
    });
  });

  app.use('/api', router);
  app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));

Login to your atlas account and click "Connect" on the "Clusters" tab 登录到您的地图集帐户,然后在“群集”选项卡上单击“连接” 在此处输入图片说明

Select "Connect application" 选择“连接应用程序”

在此处输入图片说明

Choose language and driver version (node.js driver 3.0+ on the screenshot) and copy the connection string to use in your application: 选择语言和驱动程序版本(屏幕截图上的node.js驱动程序3.0+),然后复制要在您的应用程序中使用的连接字符串:

在此处输入图片说明

Ensure you read and comprehend the smallprint - you will need to replace login and password with actual values. 确保阅读并理解了小字体-您将需要用实际值替换登录名和密码。

Then go to "Network" tab and click "Add IP": 然后转到“网络”选项卡,然后单击“添加IP”:

在此处输入图片说明

Then click "Add current IP" to access the cluster from your current system or add an IP of your server that hosts your application manually: 然后单击“添加当前IP”以从当前系统访问群集,或添加手动托管应用程序的服务器的IP:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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