Mongoose connect error

Connections

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

mongoose.connect('mongodb://127.0.0.1:27017/myapp');

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:

mongoose.connect('mongodb://username:password@host:port/database?options...');

See the mongodb connection string spec for more details.

  • Buffering
  • Error Handling
  • Options
  • Connection String Options
  • Connection Events
  • A note about keepAlive
  • Server Selection
  • Replica Set Connections
  • Replica Set Host Names
  • Multi-mongos support
  • Multiple connections
  • Connection Pools

Operation Buffering

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

mongoose.connect('mongodb://127.0.0.1:27017/myapp');
const MyModel = mongoose.model('Test', new Schema({ name: String }));
// Works
MyModel.findOne(function(error, result) { /* ... */ });

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.

const MyModel = mongoose.model('Test', new Schema({ name: String }));
// Will just hang until mongoose successfully connects
MyModel.findOne(function(error, result) { /* ... */ });

setTimeout(function() {
  mongoose.connect('mongodb://127.0.0.1:27017/myapp');
}, 60000);

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:

mongoose.set('bufferCommands', false);

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.

const schema = new Schema({
  name: String
}, {
  capped: { size: 1024 },
  bufferCommands: false,
  autoCreate: false // disable `autoCreate` since `bufferCommands` is false
});

const Model = mongoose.model('Test', schema);
// Explicitly create the collection before using it
// so the collection is capped.
await Model.createCollection();

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.

mongoose.connect('mongodb://127.0.0.1:27017/test').
  catch(error => handleError(error));

// Or:
try {
  await mongoose.connect('mongodb://127.0.0.1:27017/test');
} catch (error) {
  handleError(error);
}

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.

mongoose.connection.on('error', err => {
  logError(err);
});

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.

mongoose.connect(uri, options);

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.

Example:

const options = {
  autoIndex: false, // Don't build indexes
  maxPoolSize: 10, // Maintain up to 10 socket connections
  serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds
  socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
  family: 4 // Use IPv4, skip trying IPv6
};
mongoose.connect(uri, options);

See this page for more information about connectTimeoutMS and socketTimeoutMS

Callback

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

mongoose.connect(uri, options, function(error) {
  // Check error in initial connection. There is no 2nd param to the callback.
});

// Or using promises
mongoose.connect(uri, options).then(
  () => { /** ready to use. The `mongoose.connect()` promise resolves to mongoose instance. */ },
  err => { /** handle initial connection error */ }
);

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.

mongoose.connect('mongodb://127.0.0.1:27017/test?connectTimeoutMS=1000&bufferCommands=false&authSource=otherdb');
// The above is equivalent to:
mongoose.connect('mongodb://127.0.0.1:27017/test', {
  connectTimeoutMS: 1000
  // Note that mongoose will **not** pull `bufferCommands` from 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:

mongoose.connect(uri, { keepAlive: true, keepAliveInitialDelay: 300000 });

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.

mongoose.connect('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]' [, options]);

For example:

mongoose.connect('mongodb://user:pw@host1.com:27017,host2.com:27017,host3.com:27017/testdb');

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

mongoose.connect('mongodb://host1:port1/?replicaSet=rsName');

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:

MongoTimeoutError: Server selection timed out after 30000 ms

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

mongoose.connect(uri, {
  serverSelectionTimeoutMS: 5000 // Timeout after 5s instead of 30s
});

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.

const mongoose = require('mongoose');

const uri = 'mongodb+srv://username:badpw@cluster0-OMITTED.mongodb.net/' +
  'test?retryWrites=true&w=majority';
// Prints "MongoServerError: bad auth Authentication failed."
mongoose.connect(uri, {
  serverSelectionTimeoutMS: 5000
}).catch(err => console.log(err.reason));

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:

// Can get this error even if your connection string doesn't include
// `localhost` if `rs.conf()` reports that one replica set member has
// `localhost` as its host name.
MongooseServerSelectionError: connect ECONNREFUSED localhost:27017

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.

if (err.name === 'MongooseServerSelectionError') {
  // Contains a Map describing the state of your replica set. For example:
  // Map(1) {
  //   'localhost:27017' => ServerDescription {
  //     address: 'localhost:27017',
  //     type: 'Unknown',
  //     ...
  //   }
  // }
  console.log(err.reason.servers);
}

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.

// Connect to 2 mongos servers
mongoose.connect('mongodb://mongosA:27501,mongosB:27501', cb);

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.

const conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options);

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

const UserModel = conn.model('User', userSchema);

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.

const userSchema = new Schema({ name: String, email: String });

// The alternative to the export model pattern is the export schema pattern.
module.exports = userSchema;

// Because if you export a model as shown below, the model will be scoped
// to Mongoose's default connection.
// module.exports = mongoose.model('User', userSchema);

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:

// connections/fast.js
const mongoose = require('mongoose');

const conn = mongoose.createConnection(process.env.MONGODB_URI);
conn.model('User', require('../schemas/user'));

module.exports = conn;

// connections/slow.js
const mongoose = require('mongoose');

const conn = mongoose.createConnection(process.env.MONGODB_URI);
conn.model('User', require('../schemas/user'));
conn.model('PageView', require('../schemas/pageView'));

module.exports = conn;

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

const mongoose = require('mongoose');

module.exports = function connectionFactory() {
  const conn = mongoose.createConnection(process.env.MONGODB_URI);

  conn.model('User', require('../schemas/user'));
  conn.model('PageView', require('../schemas/pageView'));

  return conn; 
};

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:

// With object options
mongoose.createConnection(uri, { maxPoolSize: 10 });

// With connection string options
const uri = 'mongodb://127.0.0.1:27017/test?maxPoolSize=10';
mongoose.createConnection(uri);

Next Up

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

Вы можете подключиться к MongoDB с помощью метода mongoose.connect() .

mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});

Это минимум, необходимый для подключения базы данных myapp , работающей локально на порту по умолчанию (27017). Если подключение на вашем компьютере не удается, попробуйте использовать 127.0.0.1 вместо localhost .

Вы также можете указать еще несколько параметров в uri :

mongoose.connect('mongodb://username:password@host:port/database?options...', {useNewUrlParser: true});

Подробнее см. Спецификацию строки подключения mongodb .

Operation Buffering

Mongoose позволяет Вам начать использовать Ваши модели немедленно,не дожидаясь,пока mongoose установит соединение с MongoDB.

mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});
var MyModel = mongoose.model('Test', new Schema({ name: String }));

MyModel.findOne(function(error, result) {  });

Это потому, что мангуст буферизует вызовы функций модели внутри. Такая буферизация удобна, но также часто вызывает путаницу. По умолчанию Mongoose не выдаст никаких ошибок, если вы используете модель без подключения.

var MyModel = mongoose.model('Test', new Schema({ name: String }));

MyModel.findOne(function(error, result) {  });

setTimeout(function() {
  mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});
}, 60000);

Чтобы отключить буферизацию, отключите параметр bufferCommands в своей схеме . Если у вас включена bufferCommands и ваше соединение зависает, попробуйте отключить bufferCommands , чтобы проверить, не открыли ли вы соединение должным образом. Вы также можете отключить bufferCommands глобально:

mongoose.set('bufferCommands', false);

Error Handling

Существует два класса ошибок,которые могут возникать при использовании Mongoose соединения.

  • Ошибка при первоначальном подключении. Если начальное соединение не удается, Mongoose не будет пытаться восстановить соединение, он выдаст событие «ошибка», а обещание, возвращаемое mongoose.connect() будет отклонено.
  • Ошибка после первоначального подключения.Mongoose попытается переподключиться и выдаст событие «ошибка».

Чтобы обработать исходные ошибки подключения, вы должны использовать .catch() или try/catch с async / await.

mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }).
  catch(error => handleError(error));


try {
  await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
} catch (error) {
  handleError(error);
}

Для обработки ошибок после установления первоначального соединения необходимо прослушивать сообщения об ошибках при подключении.Однако,вам все равно придется обрабатывать первоначальные ошибки подключения,как показано выше.

mongoose.connection.on('error', err => {
  logError(err);
});

Options

Метод connect также принимает объект options который будет передан базовому драйверу MongoDB.

mongoose.connect(uri, options);

Полный список параметров можно найти в документации по драйверу MongoDB Node.js для connect() . Mongoose передает параметры драйверу без изменений по модулю нескольких исключений, которые описаны ниже.

  • bufferCommands — это специфичная для мангуста опция (не переданная в драйвер MongoDB), которая отключает механизм буферизации мангуста.
  • user / pass — имя пользователя и пароль для аутентификации. Эти параметры зависят от мангуста, они эквивалентны параметрам auth.user и auth.password в драйвере MongoDB .
  • autoIndex — по умолчанию mongoose автоматически строит индексы, определенные в вашей схеме, при подключении. Это отлично подходит для разработки, но не идеально для крупных производственных развертываний, поскольку построение индексов может вызвать снижение производительности. Если вы установите для autoIndex значение false, mongoose не будет автоматически создавать индексы для любой модели, связанной с этим подключением.
  • dbName — указывает, к какой базе данных следует подключиться, и отменяет любую базу данных, указанную в строке подключения. Это полезно, если вы не можете указать базу данных по умолчанию в строке подключения, например, с некоторыми синтаксическими соединениями mongodb+srv .

Ниже приведены некоторые из опций,которые важны для настройки Mongoose.

  • useNewUrlParser — базовый драйвер MongoDB устарел для своего текущего парсера строки подключения . Поскольку это серьезное изменение, они добавили флаг useNewUrlParser , чтобы позволить пользователям вернуться к старому парсеру, если они обнаружат ошибку в новом парсере. Вы должны установить useNewUrlParser: true если это не мешает вам подключиться. Обратите внимание: если вы укажете useNewUrlParser: true , вы должны указать порт в строке подключения, например, mongodb://localhost:27017/dbname . Новый парсер URL-адресов не поддерживает строки подключения, у которых нет порта, например mongodb://localhost/dbname .
  • useCreateIndex — по умолчанию False. Установите значение true , чтобы при построении индекса по умолчанию Mongoose использовала createIndex() вместо ensureIndex() чтобы избежать предупреждений об устаревании от драйвера MongoDB.
  • useFindAndModify — по умолчанию True. Установите значение false , чтобы findOneAndUpdate() и findOneAndRemove() использовали собственный findOneAndUpdate() а не findAndModify() .
  • useUnifiedTopology — по умолчанию false. Установите значение true , чтобы использовать новый механизм управления подключениями драйвера MongoDB . Вы должны установить для этого параметра значение true , за исключением маловероятного случая, когда он не позволяет поддерживать стабильное соединение.
  • promiseLibrary — устанавливает библиотеку обещаний базового драйвера .
  • poolSize — максимальное количество сокетов, которые драйвер MongoDB будет держать открытыми для этого соединения. По умолчанию poolSize равен 5. Имейте в виду, что начиная с MongoDB 3.4 MongoDB разрешает только одну операцию на сокет за раз, поэтому вы можете увеличить это значение, если обнаружите, что у вас есть несколько медленных запросов, которые блокируют более быстрые запросы от продолжение. См Медленные поезда в MongoDB и Node.js .
  • connectTimeoutMS — как долго драйвер MongoDB будет ждать перед отключением сокета из-за бездействия во время начального подключения . По умолчанию 30000. Эта опция передается прозрачно для Node.js’ socket#setTimeout() функции .
  • socketTimeoutMS — как долго драйвер MongoDB будет ждать перед отключением сокета из-за бездействия после первоначального подключения . Сокет может быть неактивным из-за отсутствия активности или длительной операции. По умолчанию установлено значение 30000 , вы должны установить это значение в 2-3 раза больше вашей самой продолжительной операции, если вы ожидаете, что некоторые из ваших операций с базой данных будут выполняться дольше 20 секунд. Этот параметр передается в Node.js socket#setTimeout() функции после того , как драйвер MongoDB успешно завершает.
  • family — соединение с использованием IPv4 или IPv6. Этот параметр передается в Node.js’ dns.lookup() функции. Если вы не укажете этот параметр, драйвер MongoDB сначала попробует IPv6, а затем IPv4 в случае сбоя IPv6. Если ваш вызов mongoose.connect(uri) занимает много времени, попробуйте mongoose.connect(uri, { family: 4 })

Следующие параметры важны для настройки Mongoose только если вы работаете без в useUnifiedTopology опции :

  • autoReconnect — базовый драйвер MongoDB будет автоматически пытаться повторно подключиться при потере соединения с MongoDB. Если вы не очень продвинутый пользователь, который хочет управлять своим собственным пулом соединений, не устанавливайте для этого параметра значение false .
  • reconnectTries — Если вы подключены к одному серверу или mongos прокси (в отличие от набора реплик), драйвер MongoDB будет пытаться восстановить соединение каждого reconnectInterval миллисекунды reconnectTries раза, а потом отказаться. Когда драйвер сдается, соединение мангуста генерирует событие reconnectFailed . Этот параметр ничего не делает для подключений набора реплик.
  • reconnectInterval — см. reconnectTries
  • bufferMaxEntries — драйвер MongoDB также имеет свой собственный механизм буферизации, который срабатывает при отключении драйвера. Установите для этого параметра значение 0 и задайте для bufferCommands значение false в ваших схемах, если вы хотите, чтобы операции с базой данных завершались немедленно, когда драйвер не подключен, а не в ожидании повторного подключения.

Example:

const options = {
  useNewUrlParser: true,
  useCreateIndex: true,
  useFindAndModify: false,
  autoIndex: false, 
  reconnectTries: Number.MAX_VALUE, 
  reconnectInterval: 500, 
  poolSize: 10, 
  
  bufferMaxEntries: 0,
  connectTimeoutMS: 10000, 
  socketTimeoutMS: 45000, 
  family: 4 
};
mongoose.connect(uri, options);

См. Эту страницу для получения дополнительной информации о connectTimeoutMS и socketTimeoutMS .

Callback

Функция connect() также принимает параметр обратного вызова и возвращает обещание .

mongoose.connect(uri, options, function(error) {
  
});


mongoose.connect(uri, options).then(
  () => {  },
  err => {  }
);

Параметры соединительной нити

Вы также можете указать параметры драйвера в строке подключения как параметры в части строки запроса URI. Это относится только к параметрам, переданным драйверу MongoDB. Вы не можете установить специфичные для Mongoose параметры, такие как bufferCommands , в строке запроса.

mongoose.connect('mongodb:

mongoose.connect('mongodb:
  connectTimeoutMS: 1000
  
});

Недостатком помещения параметров в строку запроса является то, что параметры строки запроса труднее читать. Преимущество заключается в том, что вам нужен только один параметр конфигурации, URI, а не отдельные параметры для socketTimeoutMS , connectTimeoutMS и т. Д. Лучшая практика — поместить параметры, которые, вероятно, различаются между разработкой и производством, например replicaSet или ssl , в строке подключения, и параметры, которые должны оставаться постоянными, например connectTimeoutMS или poolSize , в объекте параметров.

В документации MongoDB есть полный список поддерживаемых параметров строки подключения.


© 2010 LearnBoost
Licensed under the MIT License.
https://mongoosejs.com/docs/connections.html


Mongoose

5.7

  • SingleNestedPath

  • Virtualtype

  • Connection Events

  • Creating a Basic Custom Schema Type

Aug 1, 2019

The mongoose.connect() function is the easiest way to
connect to MongoDB using Mongoose.
Once you’ve connected, you can then create a Mongoose model and start interacting with MongoDB.

// Connect to a MongoDB server running on 'localhost:27017' and use the
// 'test' database.
await mongoose.connect('mongodb://localhost:27017/test', {
  useNewUrlParser: true // Boilerplate for Mongoose 5.x
});

// Once you're connected to MongoDB, you can create a user model and
// use it to save a user to the database.
const userSchema = new mongoose.Schema({ name: String });
const UserModel = mongoose.model('User', userSchema);

await UserModel.create({ name: 'test' });

The mongoose.connect() function returns a promise that fulfills if Mongoose successfully connects to MongoDB, or rejects if Mongoose could not connect.

const options = { useNewUrlParser: true };
// Try to connect to `nota.domain`, which should fail
const err = await mongoose.connect('mongodb://nota.domain:27017/test', options).
  catch(err => err);
// 'failed to connect to server [nota.domain:27017] on first connect'
err.message;

Many older tutorials recommend listening to connection events. This isn’t strictly necessary because Mongoose handles automatically reconnecting on its own if it loses connectivity to MongoDB after initial connection.

The promise mongoose.connect() returns only rejects if there is an error when
Mongoose is initially connecting to MongoDB. Once Mongoose successfully connects,
it automatically handles reconnecting if it loses connectivity.

The reconnectFailed Event

Mongoose handles automatically reconnecting to MongoDB. Internally, the underlying
MongoDB driver tries to reconnect reconnectTries times every reconnectInterval
milliseconds if you’re connected to a single server. You can set
reconnectTries and reconnectInterval in the mongoose.connect() options.

mongoose.connect('mongodb://localhost:27017/test', {
  useNewUrlParser: true, // Boilerplate
  // If you lose connectivity, try reconnecting every 2 seconds. After 60
  // attempts, give up and emit 'reconnectFailed'.
  reconnectTries: 60,
  reconnectInterval: 2000
})

When Mongoose gives up, it emits a ‘reconnectFailed’ event on the connection.

// If Mongoose gave up trying to reconnect, kill the process.
mongoose.connection.on('reconnectFailed', () => {
  process.nextTick(() => {
    throw new Error('Mongoose could not reconnect to MongoDB server');
  });
});

If you’re connected to a replica set, reconnectTries and reconnectInterval don’t do anything. Mongoose will continue to reconnect indefinitely if it loses connectivity to a replica set after initial connection.



Want to become your team’s MongoDB expert? «Mastering Mongoose» distills 8 years of hard-earned
lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need
to know to build production-ready full-stack apps with Node.js and MongoDB in a few days.
Get your copy!


More Mongoose Tutorials

  • Implementing Soft Delete in Mongoose
  • Using limit() with Mongoose Queries
  • How to Fix «Buffering timed out after 10000ms» Error in Mongoose
  • Using insertOne() in Mongoose
  • Mongoose on(‘delete’)
  • Enums in Mongoose
  • Mongoose find() Certain Fields

In this GitHub issue for mongoose the developer stated that it is intended behaviour to crash the Node.js process if the initial database connection to MongoDB fails. It does this instead of trying to reconnect.

In my code I catch this error because I want to log it.

var mongooseOptions = { 
    useMongoClient: true,
    reconnectInterval: 10000,
    reconnectTries: Number.MAX_VALUE 
};

mongoose.connect(connectionString, mongooseOptions)
    .catch(err => {
        logger.error('Mongodb first connection failed: ' + err.stack);
        // what to do here? - process.exit(0); maybe?
    });

But after that, what is the best practice to do?
crash the process? or write my own reconnecting logic? I maybe should mention that the mongodb.service is listed as a requirement for the node.service to start (using systemd in linux).

[Unit]
After=mongodb.service
...

I am also unsure how often I can expect to see this happen.

I have also used this guide but I cannot find a clear answer.

asked Dec 5, 2017 at 14:08

NG.'s user avatar

NG.NG.

1232 silver badges8 bronze badges

I am also looking for an answer to your question. So far in my search I believe that calling process.exit is perahps the best method. Because 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.

As of Mongoose 5.0.10 — Mongoose will not throw any errors by default if you use a model without connecting.

If your connection fails to reconnect, then your app is thinking that it is performing the model operations via the buffer when in fact it will fail.

I’ve seen developers add an additional Mongodb URI like this:

mongoose.connect(URI1||URI2);

Ultimately, you’ll want to ensure your app will always be able to connect to the database rather than perform model functions into the buffer in futility.

There is an option to disable buffering but I’m not sure how that will impact performance.

answered Mar 16, 2018 at 16:14

metal_jacke1's user avatar

Понравилась статья? Поделить с друзьями:
  • Mongodb error logs
  • Mongo server selection error
  • Mongo server error bad auth authentication failed
  • Mongo network error
  • Mongo error code 11000