Error connect econnrefused mongodb

I know I'm doing some very stupid and noobish, but I'm hoping someone can help me set up a basic database connection to mongodb from node.js on a mac. I've installed mongodb using homebrew, seems to

I know I’m doing some very stupid and noobish, but I’m hoping someone can help me set up a basic database connection to mongodb from node.js on a mac.

I’ve installed mongodb using homebrew, seems to have worked quite well. I have started the server (mongod) as the locally logged in user, and opened a second terminal and confirmed that I can connect to it by using mongo. When I run mongo I get the message «connecting to: localhost:27017/test» followed by a command prompt. Ran a few commands in the mongo shell everything seems to be working there. Left both terminals open and running.

I’ve also confirmed that I can reach the web interface at localhost:28017.

I installed node.js and added the mongoose package. Now attempting to connect using a super simple node.js app (also running as locally logged in user):

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

I receive the following error

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)

Banging my head against the wall trying to get something so simple to work. What am I missing?

Edit: Here are the logs from mongod. As you can see I tried multiple times and they’re all failing rather instantaneously:

Thu Dec  5 08:19:43.700 [initandlisten] MongoDB starting : pid=14412 port=27017 dbpath=/usr/local/var/mongodb 64-bit host=mobadmins-MacBook-Pro-3.local
           08:19:43.700 [initandlisten] db version v2.4.8
           08:19:43.700 [initandlisten] git version: nogitversion
           08:19:43.700 [initandlisten] build info: Darwin mobadmins-MacBook-Pro-3.local 12.4.0 Darwin Kernel Version 12.4.0: Wed May  1 17:57:12 PDT 2013; root:xnu-2050.24.15~1/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49
           08:19:43.700 [initandlisten] allocator: tcmalloc
           08:19:43.700 [initandlisten] options: { bind_ip: "127.0.0.1", config: "/usr/local/etc/mongod.conf", dbpath: "/usr/local/var/mongodb", logappend: "true", logpath: "/usr/local/var/log/mongodb/mongo.log", rest: true }
           08:19:43.700 [initandlisten] journal dir=/usr/local/var/mongodb/journal
           08:19:43.700 [initandlisten] recover : no journal files present, no recovery needed
           08:19:43.729 [websvr] admin web console waiting for connections on port 28017
           08:19:43.729 [initandlisten] waiting for connections on port 27017
           08:22:34.561 [initandlisten] connection accepted from 127.0.0.1:52160 #3 (1 connection now open)
           08:22:34.563 [conn3] recv(): message len 1124073472 is too large. Max is 48000000
           08:22:34.563 [conn3] end connection 127.0.0.1:52160 (0 connections now open)
           08:24:41.298 [initandlisten] connection accepted from 127.0.0.1:52166 #4 (1 connection now open)
           08:24:41.304 [conn4] end connection 127.0.0.1:52166 (0 connections now open)
           08:25:06.938 [initandlisten] connection accepted from 127.0.0.1:52168 #5 (1 connection now open)
           08:25:06.943 [conn5] end connection 127.0.0.1:52168 (0 connections now open)
           08:25:18.220 [initandlisten] connection accepted from 127.0.0.1:52172 #6 (1 connection now open)
           08:25:18.225 [conn6] end connection 127.0.0.1:52172 (0 connections now open)
           08:25:38.811 [initandlisten] connection accepted from 127.0.0.1:52175 #7 (1 connection now open)
           08:25:38.816 [conn7] end connection 127.0.0.1:52175 (0 connections now open)

Содержание

  1. Mongoose server selection error connect econnrefused
  2. Connections
  3. Operation Buffering
  4. Error Handling
  5. Options
  6. Callback
  7. Connection String Options
  8. Connection Events
  9. A note about keepAlive
  10. Replica Set Connections
  11. Server Selection
  12. Replica Set Host Names
  13. Multi-mongos support
  14. Multiple connections
  15. Connection Pools
  16. Next Up
  17. MongooseServerSelectionError: connect ECONNREFUSED :: 1: 27017 Но моя служба mongod работает

Mongoose server selection error connect econnrefused

Connections

You can connect to MongoDB with the mongoose.connect() method.

This is the minimum needed to connect the myapp database running locally on the default port (27017). If connecting fails on your machine, try using 127.0.0.1 instead of localhost .

You can also specify several more parameters in the uri :

Operation Buffering

Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB.

That’s because mongoose buffers model function calls internally. This buffering is convenient, but also a common source of confusion. Mongoose will not throw any errors by default if you use a model without connecting.

To disable buffering, turn off the bufferCommands option on your schema. If you have bufferCommands on and your connection is hanging, try turning bufferCommands off to see if you haven’t opened a connection properly. You can also disable bufferCommands globally:

Note that buffering is also responsible for waiting until Mongoose creates collections if you use the autoCreate option. If you disable buffering, you should also disable the autoCreate option and use createCollection() to create capped collections or collections with collations.

Error Handling

There are two classes of errors that can occur with a Mongoose connection.

  • Error on initial connection. If initial connection fails, Mongoose will emit an ‘error’ event and the promise mongoose.connect() returns will reject. However, Mongoose will not automatically try to reconnect.
  • Error after initial connection was established. Mongoose will attempt to reconnect, and it will emit an ‘error’ event.

To handle initial connection errors, you should use .catch() or try/catch with async/await.

To handle errors after initial connection was established, you should listen for error events on the connection. However, you still need to handle initial connection errors as shown above.

Note that Mongoose does not necessarily emit an ‘error’ event if it loses connectivity to MongoDB. You should listen to the disconnected event to report when Mongoose is disconnected from MongoDB.

Options

The connect method also accepts an options object which will be passed on to the underlying MongoDB driver.

A full list of options can be found on the MongoDB Node.js driver docs for MongoClientOptions . Mongoose passes options to the driver without modification, modulo a few exceptions that are explained below.

  • bufferCommands — This is a mongoose-specific option (not passed to the MongoDB driver) that disables Mongoose’s buffering mechanism
  • user / pass — The username and password for authentication. These options are Mongoose-specific, they are equivalent to the MongoDB driver’s auth.username and auth.password options.
  • autoIndex — By default, mongoose will automatically build indexes defined in your schema when it connects. This is great for development, but not ideal for large production deployments, because index builds can cause performance degradation. If you set autoIndex to false, mongoose will not automatically build indexes for any model associated with this connection.
  • dbName — Specifies which database to connect to and overrides any database specified in the connection string. This is useful if you are unable to specify a default database in the connection string like with some mongodb+srv syntax connections.

Below are some of the options that are important for tuning Mongoose.

  • promiseLibrary — Sets the underlying driver’s promise library.
  • maxPoolSize — The maximum number of sockets the MongoDB driver will keep open for this connection. By default, maxPoolSize is 100. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js. You may want to decrease maxPoolSize if you are running into connection limits.
  • minPoolSize — The minimum number of sockets the MongoDB driver will keep open for this connection. The MongoDB driver may close sockets that have been inactive for some time. You may want to increase minPoolSize if you expect your app to go through long idle times and want to make sure your sockets stay open to avoid slow trains when activity picks up.
  • socketTimeoutMS — How long the MongoDB driver will wait before killing a socket due to inactivity after initial connection. A socket may be inactive because of either no activity or a long-running operation. This is set to 30000 by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to Node.js socket#setTimeout() function after the MongoDB driver successfully completes.
  • family — Whether to connect using IPv4 or IPv6. This option passed to Node.js’ dns.lookup() function. If you don’t specify this option, the MongoDB driver will try IPv6 first and then IPv4 if IPv6 fails. If your mongoose.connect(uri) call takes a long time, try mongoose.connect(uri, < family: 4 >)
  • authSource — The database to use when authenticating with user and pass . In MongoDB, users are scoped to a database. If you are getting an unexpected login failure, you may need to set this option.
  • serverSelectionTimeoutMS — The MongoDB driver will try to find a server to send any given operation to, and keep retrying for serverSelectionTimeoutMS milliseconds. If not set, the MongoDB driver defaults to using 30000 (30 seconds).
  • heartbeatFrequencyMS — The MongoDB driver sends a heartbeat every heartbeatFrequencyMS to check on the status of the connection. A heartbeat is subject to serverSelectionTimeoutMS , so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a ‘disconnected’ event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits ‘disconnected’ . We recommend you do not set this setting below 1000, too many heartbeats can lead to performance degradation.

The serverSelectionTimeoutMS option also handles how long mongoose.connect() will retry initial connection before erroring out. mongoose.connect() will retry for 30 seconds by default (default serverSelectionTimeoutMS ) before erroring out. To get faster feedback on failed operations, you can reduce serverSelectionTimeoutMS to 5000 as shown below.

See this page for more information about connectTimeoutMS and socketTimeoutMS

Callback

The connect() function also accepts a callback parameter and returns a promise.

Connection String Options

You can also specify driver options in your connection string as parameters in the query string portion of the URI. This only applies to options passed to the MongoDB driver. You can’t set Mongoose-specific options like bufferCommands in the query string.

The disadvantage of putting options in the query string is that query string options are harder to read. The advantage is that you only need a single configuration option, the URI, rather than separate options for socketTimeoutMS , connectTimeoutMS , etc. Best practice is to put options that likely differ between development and production, like replicaSet or ssl , in the connection string, and options that should remain constant, like connectTimeoutMS or maxPoolSize , in the options object.

The MongoDB docs have a full list of supported connection string options. Below are some options that are often useful to set in the connection string because they are closely associated with the hostname and authentication information.

  • authSource — The database to use when authenticating with user and pass . In MongoDB, users are scoped to a database. If you are getting an unexpected login failure, you may need to set this option.
  • family — Whether to connect using IPv4 or IPv6. This option passed to Node.js’ dns.lookup() function. If you don’t specify this option, the MongoDB driver will try IPv6 first and then IPv4 if IPv6 fails. If your mongoose.connect(uri) call takes a long time, try mongoose.connect(uri, < family: 4 >)

Connection Events

Connections inherit from Node.js’ EventEmitter class, and emit events when something happens to the connection, like losing connectivity to the MongoDB server. Below is a list of events that a connection may emit.

  • connecting : Emitted when Mongoose starts making its initial connection to the MongoDB server
  • connected : Emitted when Mongoose successfully makes its initial connection to the MongoDB server, or when Mongoose reconnects after losing connectivity. May be emitted multiple times if Mongoose loses connectivity.
  • open : Emitted after ‘connected’ and onOpen is executed on all of this connection’s models.
  • disconnecting : Your app called Connection#close() to disconnect from MongoDB
  • disconnected : Emitted when Mongoose lost connection to the MongoDB server. This event may be due to your code explicitly closing the connection, the database server crashing, or network connectivity issues.
  • close : Emitted after Connection#close() successfully closes the connection. If you call conn.close() , you’ll get both a ‘disconnected’ event and a ‘close’ event.
  • reconnected : Emitted if Mongoose lost connectivity to MongoDB and successfully reconnected. Mongoose attempts to automatically reconnect when it loses connection to the database.
  • error : Emitted if an error occurs on a connection, like a parseError due to malformed data or a payload larger than 16MB.
  • fullsetup : Emitted when you’re connecting to a replica set and Mongoose has successfully connected to the primary and at least one secondary.
  • all : Emitted when you’re connecting to a replica set and Mongoose has successfully connected to all servers specified in your connection string.

When you’re connecting to a single MongoDB server (a «standalone»), Mongoose will emit ‘disconnected’ if it gets disconnected from the standalone server, and ‘connected’ if it successfully connects to the standalone. In a replica set, Mongoose will emit ‘disconnected’ if it loses connectivity to the replica set primary, and ‘connected’ if it manages to reconnect to the replica set primary.

A note about keepAlive

For long running applications, it is often prudent to enable keepAlive with a number of milliseconds. Without it, after some period of time you may start to see «connection closed» errors for what seems like no reason. If so, after reading this, you may decide to enable keepAlive :

keepAliveInitialDelay is the number of milliseconds to wait before initiating keepAlive on the socket. keepAlive is true by default since mongoose 5.2.0.

Replica Set Connections

To connect to a replica set you pass a comma delimited list of hosts to connect to rather than a single host.

To connect to a single node replica set, specify the replicaSet option.

Server Selection

The underlying MongoDB driver uses a process known as server selection to connect to MongoDB and send operations to MongoDB. If the MongoDB driver can’t find a server to send an operation to after serverSelectionTimeoutMS , you’ll get the below error:

You can configure the timeout using the serverSelectionTimeoutMS option to mongoose.connect() :

A MongoTimeoutError has a reason property that explains why server selection timed out. For example, if you’re connecting to a standalone server with an incorrect password, reason will contain an «Authentication failed» error.

Replica Set Host Names

MongoDB replica sets rely on being able to reliably figure out the domain name for each member. On Linux and OSX, the MongoDB server uses the output of the hostname command to figure out the domain name to report to the replica set. This can cause confusing errors if you’re connecting to a remote MongoDB replica set running on a machine that reports its hostname as localhost :

If you’re experiencing a similar error, connect to the replica set using the mongo shell and run the rs.conf() command to check the host names of each replica set member. Follow this page’s instructions to change a replica set member’s host name.

You can also check the reason.servers property of MongooseServerSelectionError to see what the MongoDB Node driver thinks the state of your replica set is. The reason.servers property contains a map of server descriptions.

Multi-mongos support

You can also connect to multiple mongos instances for high availability in a sharded cluster. You do not need to pass any special options to connect to multiple mongos in mongoose 5.x.

Multiple connections

So far we’ve seen how to connect to MongoDB using Mongoose’s default connection. Mongoose creates a default connection when you call mongoose.connect() . You can access the default connection using mongoose.connection .

You may need multiple connections to MongoDB for several reasons. One reason is if you have multiple databases or multiple MongoDB clusters. Another reason is to work around slow trains. The mongoose.createConnection() function takes the same arguments as mongoose.connect() and returns a new connection.

This connection object is then used to create and retrieve models. Models are always scoped to a single connection.

If you use multiple connections, you should make sure you export schemas, not models. Exporting a model from a file is called the export model pattern. The export model pattern is limited because you can only use one connection.

If you use the export schema pattern, you still need to create models somewhere. There are two common patterns. First is to export a connection and register the models on the connection in the file:

Another alternative is to register connections with a dependency injector or another inversion of control (IOC) pattern.

Connection Pools

Each connection , whether created with mongoose.connect or mongoose.createConnection are all backed by an internal configurable connection pool defaulting to a maximum size of 100. Adjust the pool size using your connection options:

Next Up

Now that we’ve covered connections, let’s take a look at models.

Источник

MongooseServerSelectionError: connect ECONNREFUSED :: 1: 27017 Но моя служба mongod работает

Каждый раз, когда я запускаю npm start в моей бэкэнд-папке, мой сервер успешно работает в течение короткого времени, а затем вскоре после этого происходит сбой. Я получаю эту ошибку обратно из командной строки:

Вот изображение, которое может помочь устранить неполадки: скриншот моего файла index.js и Mongo Compass

Я новичок в веб-разработке бэкэнда и столкнулся с этой ошибкой, пытаясь пройти курс LINKEDIN LEARNING на MERN. ссылка здесь: ВИДЕО 3 ИЗ ЭТОГО КУРСА, и я очень благодарен всем, кто хочет найти время, чтобы помочь мне решить мою проблему, спасибо!

И mongodb, и ваше приложение npm работают на одном хосте?

Эй! спасибо, что так быстро ответили! Я понятия не имею, как это проверить?

Судя по ошибке, кажется, что приложение npm подключается к mongod на том же хосте, то есть на локальном хосте. Если процесс mongod не запущен на порту 27017, вы получите отказ в подключении. Если это * nix, вы можете проверить, запущен ли процесс mongod с помощью «top» или «ps -eaf | grep mongod», а также порт с командами «netstat -tlnp».

Я очень новичок в этом и немного запутался, поэтому, пожалуйста, извините за мои глупые вопросы: я просто ввожу эти вещи прямо в командную строку? (И я использую Windows 10.)

Эй, я загрузил скриншот, который показывает, что в компасе хостом является localhost: 27017. Я думаю, это означает, что mongod работает на порту 27017, это правильно?

Похоже, он подключается к mongod, используя ipv6, а не ipv4.. MongoNetworkError: connect ECONNREFUSED ::1:27017 . Любой шанс, что вы скажете мангусту подключиться к ipv4, т.е., 127.0.0.1

ВЫ ИСПРАВИЛИ ЭТО! СПАСИБО БОЛЬШОЕ. Он работает как шарм! Я заменил первый аргумент в mongoose.connect на: «mongodb://127.0.0.1» 1000 РАЗ СПАСИБО!

Рад помочь. Я добавил ответ сейчас. Примите, если это сработало..

Источник

const mongoose = require('mongoose');


mongoose.connection.on('error', () => {
    console.log('problem')
});

mongoose.connection.on('connected', () => {
    console.log('success')
});

const testSchema = new mongoose.Schema({
    name: String
});

const Test = mongoose.model('Test', testSchema);
async function run() {
    await mongoose.connect('mongodb://localhost:27017/');
   
    await Test.create({name: 'Test'});
    console.log(await Test.find());
    console.log('yo');
    await mongoose.connection.dropDatabase();
}

run();
console.log('hello?')
$ node ./10917.js
hello?
problem
C:UsersDaniel DiazDesktopWorkdebuggingJavaScriptnode_modulesmongooselibconnection.js:797
  const serverSelectionError = new ServerSelectionError();
                               ^

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at NativeConnection.Connection.openUri (C:UsersDaniel DiazDesktopWorkdebuggingJavaScriptnode_modulesmongooselibconnection.js:797:32)
    at C:UsersDaniel DiazDesktopWorkdebuggingJavaScriptnode_modulesmongooselibindex.js:330:10
    at C:UsersDaniel DiazDesktopWorkdebuggingJavaScriptnode_modulesmongooselibhelperspromiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:UsersDaniel DiazDesktopWorkdebuggingJavaScriptnode_modulesmongooselibhelperspromiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (C:UsersDaniel DiazDesktopWorkdebuggingJavaScriptnode_modulesmongooselibindex.js:1151:10)
    at Mongoose.connect (C:UsersDaniel DiazDesktopWorkdebuggingJavaScriptnode_modulesmongooselibindex.js:329:20)
    at run (C:UsersDaniel DiazDesktopWorkdebuggingJavaScript10917.js:18:20)
    at Object.<anonymous> (C:UsersDaniel DiazDesktopWorkdebuggingJavaScript10917.js:26:1)
    at Module._compile (node:internal/modules/cjs/loader:1095:14) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        _hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 10945158,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:UsersDaniel DiazDesktopWorkdebuggingJavaScriptnode_modulesmongoosenode_modulesmongodblibcmapconnect.js:293:20)
            at Socket.<anonymous> (C:UsersDaniel DiazDesktopWorkdebuggingJavaScriptnode_modulesmongoosenode_modulesmongodblibcmapconnect.js:267:22)
            at Object.onceWrapper (node:events:510:26)
            at Socket.emit (node:events:390:28)
            at emitErrorNT (node:internal/streams/destroy:164:8)
            at emitErrorCloseNT (node:internal/streams/destroy:129:3)
            at processTicksAndRejections (node:internal/process/task_queues:83:21)
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}

Node.js v17.0.1

Hello Readers,

I came across a solution while working on mongodb and would like to share with you all in case you face any such problem while working on mongodb.

If you are coming across the error like the following:

Connection error:  { [MongoError: connect ECONNREFUSED] name: 'MongoError', message: 'connect ECONNREFUSED' }

while trying to connect to mongodb on Ubuntu, you can use the following process to resolve it and gain the mongodb connection again.

Reason behind the above error

The above type of error could occur If you forget to close the database connection after you finish your work last time or If your system/server got crashed during any work process.

Actually the mongodb keeps a lock file while it’s running or started and delete the file when stopped. But when the system got crashed or you close the terminal without closing the mongodb server, it keeps the old lock file and terminate / shutdown mongodb whenever you start the server next time and tried to connect to database. You can check its log file in /var/log/mongodb/mongod.log for the following line:

2015-05-11T09:07:28.216+0530 [initandlisten] exception in initAndListen: 12596 old lock file, terminating
2015-05-11T09:07:28.216+0530 [initandlisten] dbexit: 
2015-05-11T09:07:28.216+0530 [initandlisten] shutdown: going to close listening sockets...
2015-05-11T09:07:28.216+0530 [initandlisten] shutdown: going to flush diaglog...
2015-05-11T09:07:28.216+0530 [initandlisten] shutdown: going to close sockets...
2015-05-11T09:07:28.216+0530 [initandlisten] shutdown: waiting for fs preallocator...
2015-05-11T09:07:28.216+0530 [initandlisten] shutdown: closing all files...
2015-05-11T09:07:28.216+0530 [initandlisten] closeAllFiles() finished
2015-05-11T09:07:28.216+0530 [initandlisten] dbexit: really exiting now

The following text above clearly shows the existance of old lock file which terminating the connection.

Solution:

  1. To resolve the issue the safest process is to to follow MongoDB’s Durability and Repair guide and to do that you can use the following command in the terminal.
    sudo -u mongodb mongod --repair --dbpath /var/lib/mongodb/
    

    and then..

    sudo service mongod start
    
  2. -OR- If this is the starting of your project and you have not been using the database, then you can remove the lock file manually.

Hope this could be helpful and save some of your valuable time. Keep Reading..

#javascript #mongodb #mongoose

Вопрос:

Я пытаюсь уже более 2 часов, пытаясь выяснить, что не так с этой базой данных. Я все перепробовал. От переустановки сервера, перезапуска процессов, перезагрузки и многого другого. Он продолжает выдавать мне эту ошибку при попытке подключения:

 const serverSelectionError = new ServerSelectionError();
                               ^

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at NativeConnection.Connection.openUri (D:TheShedMX_node_modulesmongooselibconnection.js:797:32)
    at D:TheShedMX_node_modulesmongooselibindex.js:330:10
    at D:TheShedMX_node_modulesmongooselibhelperspromiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (D:TheShedMX_node_modulesmongooselibhelperspromiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (D:TheShedMX_node_modulesmongooselibindex.js:1151:10)
    at Mongoose.connect (D:TheShedMX_node_modulesmongooselibindex.js:329:20)
    at module.exports (D:TheShedMX_otherDBmong.js:4:20)
    at D:TheShedMX_app.js:195:37
    at Object.<anonymous> (D:TheShedMX_app.js:197:3) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        _hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 1421094,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (D:TheShedMX_node_modulesmongodblibcmapconnect.js:293:20)
            at Socket.<anonymous> (D:TheShedMX_node_modulesmongodblibcmapconnect.js:267:22)
            at Object.onceWrapper (node:events:510:26)
            at Socket.emit (node:events:390:28)
            at emitErrorNT (node:internal/streams/destroy:164:8)
            at emitErrorCloseNT (node:internal/streams/destroy:129:3)
            at processTicksAndRejections (node:internal/process/task_queues:83:21)
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}
 

Эта ошибка не будет устранена независимо от того, что я делаю. Сервер MongoDB запущен, я проверил, выполнив> показать базы данных, и они перечислены в полном порядке. Кроме того, C:/data/db существует, и это тоже прекрасно.
Что мне делать?
Вот мой код подключения:

 (async () => {
    await require('./other/DB/mong')();
    console.log("Connected to Database.");
})();
 

и вот ./other/DB/mong:

 var mongoose = require("mongoose");

module.exports = async () => {
    await mongoose.connect('mongodb://localhost:27017/MX', {
        keepAlive: true,
        useNewUrlParser: true,
        useUnifiedTopology: true
    });
    return mongoose;
}
 

Комментарии:

1. Что происходит, когда вы заменяете localhost на 127.0.0.1?

Ответ №1:

MongoDB по умолчанию не привязывается к localhost на ipv6.

Если вы хотите, чтобы он прослушивал ::1, вам нужно будет включить net.ipv6 и либо включить net.bindIpAll, либо явно указать адрес обратной связи в net.bindIp

Комментарии:

1. Спасибо! это помогло мне. Для тех, кто установил mongo через homebrew, вы можете отредактировать конфигурацию с помощью vim, используя: vim /opt/homebrew/etc/mongod.conf

Ответ №2:

Я только что нашел решение в Интернете, если вы используете последнюю версию nodejs (v17.x), попробуйте обновить URL mongodb с localhost на 127.0.0.1

Это сработало для меня: slightly_smiling_face:

Комментарии:

1. Я тоже! Как странно, я весь день использовал его нормально, начал новый проект и внезапно должен был реализовать это изменение: большое спасибо!

Ответ №3:

Обновил мой URL-адрес mongodb с ‘mongodb: // localhost: 27017 / student’ на ‘mongodb: // 127.0.0.1: 27017 / student’, и у меня все получилось

Ответ №4:

вы также можете использовать mongodb://0.0.0.0:27017/database_name

Я знаю, что делаю что-то очень глупое и нубское, но я надеюсь, что кто-нибудь поможет мне настроить базовое подключение к базе данных к mongodb из node.js на Mac.

Я установил mongodb с помощью доморощенного, похоже, работал довольно хорошо. Я запустил сервер (mongod) как локальный пользователь, открыл второй терминал и подтвердил, что могу подключиться к нему с помощью mongo. Когда я запускаю mongo, я получаю сообщение «connecting to: localhost: 27017/test», за которым следует командная строка. Запустил несколько команд в оболочке монго, вроде все работает. Оставил оба терминала открытыми и работающими.

Я также подтвердил, что могу получить доступ к веб-интерфейсу по адресу localhost:28017.

Я установил node.js и добавил пакет mongoose. Теперь пытаемся подключиться с помощью очень простого приложения node.js (также работающего как локальный пользователь):

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

Я получаю следующую ошибку

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)

Бьюсь головой о стену, пытаясь заставить работать что-то настолько простое. Что мне не хватает?

Изменить: вот журналы из mongod. Как вы можете видеть, я пытался несколько раз, и все они терпят неудачу довольно мгновенно:

Thu Dec  5 08:19:43.700 [initandlisten] MongoDB starting : pid=14412 port=27017 dbpath=/usr/local/var/mongodb 64-bit host=mobadmins-MacBook-Pro-3.local
           08:19:43.700 [initandlisten] db version v2.4.8
           08:19:43.700 [initandlisten] git version: nogitversion
           08:19:43.700 [initandlisten] build info: Darwin mobadmins-MacBook-Pro-3.local 12.4.0 Darwin Kernel Version 12.4.0: Wed May  1 17:57:12 PDT 2013; root:xnu-2050.24.15~1/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49
           08:19:43.700 [initandlisten] allocator: tcmalloc
           08:19:43.700 [initandlisten] options: { bind_ip: "127.0.0.1", config: "/usr/local/etc/mongod.conf", dbpath: "/usr/local/var/mongodb", logappend: "true", logpath: "/usr/local/var/log/mongodb/mongo.log", rest: true }
           08:19:43.700 [initandlisten] journal dir=/usr/local/var/mongodb/journal
           08:19:43.700 [initandlisten] recover : no journal files present, no recovery needed
           08:19:43.729 [websvr] admin web console waiting for connections on port 28017
           08:19:43.729 [initandlisten] waiting for connections on port 27017
           08:22:34.561 [initandlisten] connection accepted from 127.0.0.1:52160 #3 (1 connection now open)
           08:22:34.563 [conn3] recv(): message len 1124073472 is too large. Max is 48000000
           08:22:34.563 [conn3] end connection 127.0.0.1:52160 (0 connections now open)
           08:24:41.298 [initandlisten] connection accepted from 127.0.0.1:52166 #4 (1 connection now open)
           08:24:41.304 [conn4] end connection 127.0.0.1:52166 (0 connections now open)
           08:25:06.938 [initandlisten] connection accepted from 127.0.0.1:52168 #5 (1 connection now open)
           08:25:06.943 [conn5] end connection 127.0.0.1:52168 (0 connections now open)
           08:25:18.220 [initandlisten] connection accepted from 127.0.0.1:52172 #6 (1 connection now open)
           08:25:18.225 [conn6] end connection 127.0.0.1:52172 (0 connections now open)
           08:25:38.811 [initandlisten] connection accepted from 127.0.0.1:52175 #7 (1 connection now open)
           08:25:38.816 [conn7] end connection 127.0.0.1:52175 (0 connections now open)

Понравилась статья? Поделить с друзьями:
  • Error conflicting types for си
  • Error conflicted subnet addresses
  • Error configuring sdk pycharm
  • Error configuring s3 backend no valid credential sources for s3 backend found
  • Error constexpr does not name a type