简体   繁体   English

无法使用猫鼬连接到 mongodb 图集

[英]unable to connect to mongodb atlas with mongoose

i need help!!!我需要帮助!!! I tried connecting to mongodb atlas with my connection string but I'm unable to.我尝试使用我的连接字符串连接到 mongodb atlas,但我无法连接。 I'm not sure how to proceed.我不知道如何继续。 i have a barebones application.我有一个准系统应用程序。 I'm getting a connection error (a mongooseServerSelectionError) and an unhandled Promise Rejection Warning.我收到一个连接错误(一个 mongooseServerSelectionError)和一个未处理的 Promise Rejection Warning。

Here is the error:这是错误:

 connection error:  MongooseError [MongooseServerSelectionError]: connect ECONNREFUSED 127.0.0.1:27017
   at new MongooseServerSelectionError (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/error/serverSelection.js:22:11)
   at NativeConnection.Connection.openUri (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/connection.js:808:32)
   at Mongoose.connect (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/index.js:333:15)
   at Object.<anonymous> (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/server/db/index.js:4:10)
   at Module._compile (internal/modules/cjs/loader.js:1157:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
   at Module.load (internal/modules/cjs/loader.js:1001:32)
   at Function.Module._load (internal/modules/cjs/loader.js:900:14)
   at Module.require (internal/modules/cjs/loader.js:1043:19)
   at require (internal/modules/cjs/helpers.js:77:18)
   at Object.<anonymous> (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/server/bin.js:33:10)
   at Module._compile (internal/modules/cjs/loader.js:1157:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
   at Module.load (internal/modules/cjs/loader.js:1001:32)
   at Function.Module._load (internal/modules/cjs/loader.js:900:14)
   at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
 message: 'connect ECONNREFUSED 127.0.0.1:27017',
 name: 'MongooseServerSelectionError',
 reason: TopologyDescription {
   type: 'Single',
   setName: null,
   maxSetVersion: null,
   maxElectionId: null,
   servers: Map { 'localhost:27017' => [ServerDescription] },
   stale: false,
   compatible: true,
   compatibilityError: null,
   logicalSessionTimeoutMinutes: null,
   heartbeatFrequencyMS: 10000,
   localThresholdMS: 15,
   commonWireVersion: null
 },
 [Symbol(mongoErrorContextSymbol)]: {}
}
(node:9182) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
   at new MongooseServerSelectionError (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/error/serverSelection.js:22:11)
   at NativeConnection.Connection.openUri (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/connection.js:808:32)
   at Mongoose.connect (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/index.js:333:15)
   at Object.<anonymous> (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/server/db/index.js:4:10)
   at Module._compile (internal/modules/cjs/loader.js:1157:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
   at Module.load (internal/modules/cjs/loader.js:1001:32)
   at Function.Module._load (internal/modules/cjs/loader.js:900:14)
   at Module.require (internal/modules/cjs/loader.js:1043:19)
   at require (internal/modules/cjs/helpers.js:77:18)
   at Object.<anonymous> (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/server/bin.js:33:10)
   at Module._compile (internal/modules/cjs/loader.js:1157:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
   at Module.load (internal/modules/cjs/loader.js:1001:32)
   at Function.Module._load (internal/modules/cjs/loader.js:900:14)
   at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
(node:9182) 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:9182) [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.

Here is my code:这是我的代码:

i give directions for which uri to connect to, set up the connection through mongoose, export the db and open the connection in app.js ...我给出了要连接的 uri 的指示,通过 mongoose 设置连接,导出数据库并在app.js 中打开连接......

inside db/index.js :db/index.js 中

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// const uri = require('../../keys.js').mongodb.dbURI;
mongoose.connect("mongodb://localhost/test", { useNewUrlParser: true, useUnifiedTopology: true});
// mongoose.connect(process.env.MONGODB_URL || uri, { useNewUrlParser: true, useUnifiedTopology: true});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));

module.exports = db;

Inside app.js :app.js 中

console.log('NODE_ENV :::', process.env.NODE_ENV);
if (process.env.NODE_ENV === 'PRODUCTION') {
    var app = require('./prod.app.js'); 
} else {
    var app = require('./dev.app.js');
}
var express = require('express');
var path = require('path');
var routes = require('./db/routes/index.js');
var http = require('http');
var favicon = require('serve-favicon');
var PORT = 3000;

/* 
 * shared code in production and development 
*/

// favicon - 3 ways - middleware, static, html 
app.use(favicon(path.join(__dirname, '../public/images/favicon.ico')));
// app.use('/favicon.ico', express.static(path.join(__dirname, '../public/images/favicon.ico')));
// app.use('images/favicon.ico', express.static(path.join(__dirname, '../public/images/favicon.ico')));

app.use(express.json());
app.use(express.urlencoded({ extended: true}));

// static files
app.use(express.static(path.join(__dirname, "../client")));
app.use(express.static(path.join(__dirname, "../public")));

// db - mongo
var db = require('./db/index.js');
db.once("open", function (err) {
    // console.log('db::: ', db);
    if (err) {
        return console.error(err);
    } else {
        console.log("Successfully connected to mongodb");
    }
})

// routes
app.use(routes); 

// serve index.html if can't find the route
app.use('*', function (req, res, next) {
    console.log("...serving index.html file from the public folder")
    res.sendFile(path.join(__dirname, '../public/index.html'));
});

// create server 
var server = http.createServer(app);
server.listen(PORT);
console.log(`server listening on post ${PORT}`);

thank you for looking into this for me谢谢你帮我调查这个

Did you have this line in your app.js app.use(cors()) ?你的 app.js app.use(cors())有这行吗?

Try to delete this line and delete everything that involves cors.尝试删除此行并删除所有涉及 cors 的内容。

If this don't work, check your IP Whitelist inside Network Access in MongoDB Atlas and add your current IP or write this 0.0.0.0/0 to allow all IPs.如果这不起作用,请检查 MongoDB Atlas 中网络访问内的 IP 白名单并添加您当前的 IP 或写入此 0.0.0.0/0 以允许所有 IP。

check your IP is enabled by mongodb atlas.检查您的 IP 是否由 mongodb atlas 启用。 you should give access to your computer IP address from mongodb atlas.您应该允许从 mongodb atlas 访问您的计算机 IP 地址。 go to the network access (left side bar) enter your IP or enter 0.0.0.0 to access all IP.转到网络访问(左侧栏)输入您的 IP 或输入 0.0.0.0 以访问所有 IP。

set your current ip address as 0.0.0.0/0 in mongoDB ATLAS in Connection ip address.在连接 ip 地址的 mongoDB ATLAS 中将您当前的 ip 地址设置为 0.0.0.0/0。 It will allow to connect all ip address.它将允许连接所有IP地址。

尝试添加 Atlas 提供的 url 以连接您的应用:

mongoose.connect("<URLprovidedByAtlas>", { useNewUrlParser: true, useUnifiedTopology: true});

兄弟更新mongodb atlus中的(ip)地址。它会帮助你

Try to check your internet connection and if you having your IP address correctly.尝试检查您的互联网连接,以及您的 IP 地址是否正确。

https://github.com/Automattic/mongoose/issues/8180#issuecomment-552161146 https://github.com/Automattic/mongoose/issues/8180#issuecomment-552161146

This worked for me.这对我有用。 I first changed the ip address to 0.0.0.0/0 and removed app.use(cores()).我首先将 ip 地址更改为 0.0.0.0/0 并删除了 app.use(cores())。 Then I downloaded mongoDB compass and connected to the data base.然后我下载了mongoDB指南针并连接到数据库。 After that the same URI was used in index.js.之后在 index.js 中使用了相同的 URI。 There is a difference in inputting password in the URI and Compass.在 URI 和 Compass 中输入密码是有区别的。 In compass you don't need to encode the password(if you have special characters).在指南针中,您不需要对密码进行编码(如果您有特殊字符)。 If you connect using compass and paste that link in the index.js you don't need to encode the password.如果您使用指南针连接并将该链接粘贴到 index.js 中,则不需要对密码进行编码。

检查您是否通过 ./mongod 在终端中启动了数据库

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

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