Connections连接
You can connect to MongoDB with the 您可以使用mongoose.connect()
method.mongoseconnect()
方法连接到MongoDB。.
mongoose.connect('mongodb://127.0.0.1:27017/myapp');
This is the minimum needed to connect the 这是连接在默认端口(27017)上本地运行的myapp
database running locally on the default port (27017). myapp
数据库所需的最低值。If connecting fails on your machine, try using 如果在您的计算机上连接失败,请尝试使用127.0.0.1
instead of localhost
.127.0.0.1
而不是localhost
。
You can also specify several more parameters in the 您还可以在uri
:uri
中指定其他几个参数:
mongoose.connect('mongodb://username:password@host:port/database?options...');
See the mongodb connection string spec for more details.有关更多详细信息,请参阅mongodb连接字符串规范。
Buffering缓冲Error Handling错误处理Options选项Connection String Options连接字符串选项Connection Events连接事件A note about keepAlive关于keepAlive
的备忘Server Selection服务器选择Replica Set Connections副本集连接Replica Set Host Names副本集主机名Multi-mongos support多mongos支持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可以让您立即开始使用模型,而无需等待Mongoose建立与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在内部缓冲模型函数调用。这种缓冲很方便,但也是造成混乱的常见原因。Mongoose will not throw any errors by default if you use a model without connecting.如果您在没有连接的情况下使用模型,Mongoose默认情况下不会抛出任何错误。
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. bufferCommands
选项。If you have 如果你打开了bufferCommands
on and your connection is hanging, try turning bufferCommands
off to see if you haven't opened a connection properly. bufferCommands
,而你的连接挂起了,试着关闭bufferCommands
,看看你是否没有正确打开连接。You can also disable 您也可以全局禁用bufferCommands
globally:bufferCommands
:
mongoose.set('bufferCommands', false);
Note that buffering is also responsible for waiting until Mongoose creates collections if you use the 请注意,如果您使用autoCreate
option. autoCreate
选项,缓冲还负责等待Mongoose创建集合。If you disable buffering, you should also disable the 如果禁用缓冲,还应该禁用autoCreate
option and use createCollection()
to create capped collections or collections with collations.autoCreate
选项,并使用createCollection()
创建封顶集合或带有排序规则的集合。
const schema = new Schema({
name: String
}, {
capped: { size: 1024 },
bufferCommands: false,
autoCreate: false // disable `autoCreate` since `bufferCommands` is false禁用`autoCreate`,因为`bufferCommands`为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.Mongoose连接可能会出现两类错误。
Error on initial connection.初始连接时出错。If initial connection fails, Mongoose will emit an 'error' event and the promise如果初始连接失败,Mongoose将发出一个“error”事件,并且返回的promisemongoose.connect()
returns will reject.mongoose.connect()
将被拒绝。However, Mongoose will not automatically try to reconnect.然而,Mongoose不会自动尝试重新连接。Error after initial connection was established.建立初始连接后出错。Mongoose will attempt to reconnect, and it will emit an 'error' event.Mongoose将尝试重新连接,它将发出一个'error'
事件。
To handle initial connection errors, you should use 要处理初始连接错误,应该使用.catch()
or try/catch
with async/await..catch()
或带有async
/await
的try/catch
。
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. 请注意,如果Mongoose失去了与MongoDB的连接,它不一定会发出“错误”事件。You should listen to the 当Mongoose与MongoDB断开连接时,您应该监听disconnected
event to report when Mongoose is disconnected from MongoDB.disconnected
连接的事件以报告。
Options选项
The connect
method also accepts an options
object which will be passed on to the underlying MongoDB driver.connect
方法还接受一个options
对象,该对象将传递给底层MongoDB驱动程序。
mongoose.connect(uri, options);
A full list of options can be found on the MongoDB Node.js driver docs for 选项的完整列表可以在MongoClientOptions
. MongoClientOptions
的MongoDB Node.js驱动程序文档中找到。Mongoose passes options to the driver without modification, modulo a few exceptions that are explained below.Mongoose在不修改的情况下将选项传递给驱动程序,模块化了下面解释的一些例外情况。
bufferCommands
-This is a mongoose-specific option (not passed to the MongoDB driver) that disables Mongoose's buffering mechanism这是一个特定于mongoose的选项(未传递给MongoDB驱动程序),用于禁用mongoose缓冲机制user
/pass
-The username and password for authentication.用于身份验证的用户名和密码。These options are Mongoose-specific, they are equivalent to the MongoDB driver's这些选项是特定于Mongoose的,相当于MongoDB驱动程序auth.username
andauth.password
options.auth.username
和auth.password
选项。autoIndex
-By default, mongoose will automatically build indexes defined in your schema when it connects.默认情况下,mongoose在连接时会自动构建在您的架构中定义的索引。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.autoIndex
设置为false
,mongoose将不会自动为与此连接关联的任何模型生成索引。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.mongodb+srv
语法连接),这将非常有用。
Below are some of the options that are important for tuning Mongoose.以下是一些对调优Mongoose很重要的选项。
promiseLibrary
-Sets the underlying driver's promise library.设置基础驱动程序的promise库。maxPoolSize
-The maximum number of sockets the MongoDB driver will keep open for this connection.MongoDB驱动程序将为此连接保持打开的最大套接字数。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.maxPoolSize
为100。请记住,MongoDB一次只允许每个套接字进行一次操作,因此如果您发现有一些较慢的查询阻碍了较快的查询的进行,则可能需要增加这一操作。See Slow Trains in MongoDB and Node.js.请参阅MongoDB和Node.js中的慢速列车。You may want to decrease如果遇到连接限制,您可能需要降低maxPoolSize
if you are running into connection limits.maxPoolSize
。minPoolSize
-The minimum number of sockets the MongoDB driver will keep open for this connection.MongoDB驱动程序将为该连接保持打开的最小套接字数。The MongoDB driver may close sockets that have been inactive for some time.MongoDB驱动程序可能会关闭一段时间以来一直处于非活动状态的套接字。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.minPoolSize
。socketTimeoutMS
-How long the MongoDB driver will wait before killing a socket due to inactivity after initial connection.MongoDB驱动程序在初始连接后由于不活动而杀死套接字之前要等待多长时间。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.30000
,如果您希望某些数据库操作的运行时间超过20秒,则应将其设置为运行时间最长的操作的2-3倍。This option is passed to Node.js此选项在MongoDB驱动程序成功完成后传递给Node.jssocket#setTimeout()
function after the MongoDB driver successfully completes.socket#setTimeout()
函数。family
-Whether to connect using IPv4 or IPv6.是使用IPv4还是IPv6进行连接。This option passed to Node.js'此选项传递给Node.js的dns.lookup()
function.dns.lookup()
函数。If you don't specify this option, the MongoDB driver will try IPv6 first and then IPv4 if IPv6 fails.如果不指定此选项,MongoDB驱动程序将首先尝试IPv6,如果IPv6失败,则会尝试IPv4。If your如果您的mongoose.connect(uri)
call takes a long time, trymongoose.connect(uri, { family: 4 })
mongoose.connect(uri)
调用需要很长时间,请尝试mongoose.connect(uri, { family: 4 })
。authSource
-The database to use when authenticating with使用user
andpass
.user
和pass
进行身份验证时要使用的数据库。In MongoDB, users are scoped to a database. If you are getting an unexpected login failure, you may need to set this option.在MongoDB中,用户的作用域是一个数据库。如果出现意外登录失败,则可能需要设置此选项。serverSelectionTimeoutMS
-The MongoDB driver will try to find a server to send any given operation to, and keep retrying forMongoDB驱动程序将尝试找到一个服务器来发送任何给定的操作,并在serverSelectionTimeoutMS
milliseconds.serverSelectionTimeoutMS
毫秒内不断重试。If not set, the MongoDB driver defaults to using如果未设置,MongoDB驱动程序默认使用30000
(30 seconds).30000
(30秒)。heartbeatFrequencyMS
-The MongoDB driver sends a heartbeat everyMongoDB驱动程序在每个heartbeatFrequencyMS
to check on the status of the connection.heartbeatFrequencyMS
发送一个心跳来检查连接状态。A heartbeat is subject to心跳受serverSelectionTimeoutMS
, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default.serverSelectionTimeoutMS
的约束,因此MongoDB驱动程序将在默认情况下重试失败的心跳长达30秒。Mongoose only emits aMongoose只在检测信号失败后才会发出'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'
.'disconnected'
事件,因此您可能需要减少此设置,以减少服务器停机和Mongoose发出“断开连接”之间的时间。We recommend you do not set this setting below 1000, too many heartbeats can lead to performance degradation.我们建议您不要将此设置设置为低于1000,过多的心跳会导致性能下降。
The serverSelectionTimeoutMS
option also handles how long mongoose.connect()
will retry initial connection before erroring out. serverSelectionTimeoutMS
选项还处理mongose.connect()
在出错之前重试初始连接的时间。mongoose.connect()
will retry for 30 seconds by default (default 默认情况下将重试30秒(默认serverSelectionTimeoutMS
) before erroring out. serverSelectionTimeoutMS
),然后出错。To get faster feedback on failed operations, you can reduce 为了更快地获得失败操作的反馈,您可以将serverSelectionTimeoutMS
to 5000 as shown below.serverSelectionTimeoutMS
减少到5000,如下所示。
Example:示例:
const options = {
autoIndex: false, // Don't build indexes不建立索引
maxPoolSize: 10, // Maintain up to 10 socket connections保持多达10个套接字连接
serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds继续尝试发送操作5秒
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity处于非活动状态45秒后关闭套接字
family: 4 // Use IPv4, skip trying IPv6使用IPv4,跳过尝试IPv6
};
mongoose.connect(uri, options);
See this page for more information about 有关connectTimeoutMS
and socketTimeoutMS
connectTimeoutMS
和socketTimeoutMS
的更多信息,请参阅本页。
Callback回调
The connect()
function also accepts a callback parameter and returns a promise.connect()
函数还接受一个回调参数并返回一个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.即用即用。`mongose.connect()` promise解析为mongose实例。 */ },
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. 您还可以在连接字符串中指定驱动程序选项作为URI的查询字符串部分中的参数。This only applies to options passed to the MongoDB driver. 这只适用于传递给MongoDB驱动程序的选项。You can't set Mongoose-specific options like 您不能在查询字符串中设置特定于Mongoose的选项,如bufferCommands
in the query string.bufferCommands
。
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请注意,mongoose将**不会**从查询字符串中提取`bufferCommands`
});
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 优点是您只需要一个配置选项,即URI,而不需要socketTimeoutMS
, connectTimeoutMS
, etc. socketTimeoutMS
、connectTimeoutMS
等单独的选项。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.replicaSet
或ssl
)放在连接字符串中,并将应该保持不变的选项(例如connectTimeoutMS
或maxPoolSize
)放在选项对象中。
The MongoDB docs have a full list of supported connection string options. MongoDB文档有一个完整的受支持的连接字符串选项列表。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
andpass
.user
和pass
进行身份验证时要使用的数据库。In MongoDB, users are scoped to a database.在MongoDB中,用户的作用域是一个数据库。If you are getting an unexpected login failure, you may need to set this option.如果出现意外登录失败,则可能需要设置此选项。family
-Whether to connect using IPv4 or IPv6.是使用IPv4还是IPv6进行连接。This option passed to Node.js'此选项传递给Node.js的dns.lookup()
function.dns.lookup()
函数。If you don't specify this option, the MongoDB driver will try IPv6 first and then IPv4 if IPv6 fails.如果不指定此选项,MongoDB驱动程序将首先尝试IPv6,如果IPv6失败,则会尝试IPv4。If your如果mongoose.connect(uri)
call takes a long time, trymongoose.connect(uri)
调用需要很长时间,请尝试mongoose.connect(uri, { family: 4 })
。
Connection Events连接事件
Connections inherit from Node.js' 连接继承自Node.js的EventEmitter
class, and emit events when something happens to the connection, like losing connectivity to the MongoDB server. EventEmitter
类,并在连接发生问题时发出事件,例如失去与MongoDB服务器的连接。Below is a list of events that a connection may emit.以下是连接可能发出的事件列表。
connecting
: Emitted when Mongoose starts making its initial connection to the MongoDB server:当Mongoose开始与MongoDB服务器进行初始连接时发出connected
: Emitted when Mongoose successfully makes its initial connection to the MongoDB server, or when Mongoose reconnects after losing connectivity.:当Mongoose成功地与MongoDB服务器建立初始连接时,或当Mongouse在失去连接后重新连接时发出。May be emitted multiple times if Mongoose loses connectivity.如果Mongoose失去连接,可能会多次发出。open
: Emitted after:在'connected'
andonOpen
is executed on all of this connection's models.'connected'
之后发出,并且在此连接的所有模型上执行onOpen
。disconnecting
: Your app called Connection#close() to disconnect from MongoDB:您的应用程序调用了Connection#close()
以断开与MongoDB的连接disconnected
: Emitted when Mongoose lost connection to the MongoDB server.:当Mongoose失去与MongoDB服务器的连接时发出。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.:在Connection#close()
成功关闭连接后发出。If you call如果调用conn.close()
, you'll get both a 'disconnected' event and a 'close' event.conn.close()
,您将同时得到一个'disconnected'
事件和一个'close'
事件。reconnected
: Emitted if Mongoose lost connectivity to MongoDB and successfully reconnected.:如果Mongoose失去了与MongoDB的连接并成功重新连接,则发出。Mongoose attempts to automatically reconnect when it loses connection to the database.当Mongoose失去与数据库的连接时,它会尝试自动重新连接。error
: Emitted if an error occurs on a connection, like a:如果连接上发生错误,如由于数据格式错误或负载大于16MB而导致的parseError
due to malformed data or a payload larger than 16MB.parseError
,则会发出。fullsetup
: Emitted when you're connecting to a replica set and Mongoose has successfully connected to the primary and at least one secondary.:当您连接到副本集并且Mongoose已成功连接到主副本集和至少一个辅助副本集时发出。all
: Emitted when you're connecting to a replica set and Mongoose has successfully connected to all servers specified in your connection string.:当您连接到副本集并且Mongoose已成功连接到连接字符串中指定的所有服务器时发出。
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. 当您连接到单个MongoDB服务器(“独立服务器”)时,如果Mongoose与独立服务器断开连接,它将发出'disconnected'
(已断开),如果它成功连接到独立服务器,则发出'connected'
(已连接)。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.在副本集中,如果Mongoose失去了与副本集主副本集的连接,它将发出'disconnected'
,如果它设法重新连接到副本集主复制集,则发出'connected'
。
A note about keepAlive关于keepAlive的笔记
For long running applications, it is often prudent to enable 对于长时间运行的应用程序,启用keepAlive
with a number of milliseconds. keepAlive
通常需要几毫秒的时间,这是非常谨慎的。Without it, after some period of time you may start to see 如果没有它,一段时间后,你可能会开始看到"connection closed"
errors for what seems like no reason. "connection closed"
的错误,这似乎是没有原因的。If so, after reading this, you may decide to enable 如果是这样,阅读本文后,您可能会决定启用keepAlive
:keepAlive
:
mongoose.connect(uri, { keepAlive: true, keepAliveInitialDelay: 300000 });
keepAliveInitialDelay
is the number of milliseconds to wait before initiating 是在套接字上启动keepAlive
on the socket. keepAlive
之前等待的毫秒数。keepAlive
is true by default since mongoose 5.2.0.默认情况下为true
,自从mongoose5.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.replicaSet
选项。
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. 底层的MongoDB驱动程序使用一个称为服务器选择的过程来连接到MongoDB并将操作发送到MongoDB。If the MongoDB driver can't find a server to send an operation to after 如果MongoDB驱动程序在serverSelectionTimeoutMS
, you'll get the below error:serverSelectionTimeoutMS
之后找不到要发送操作的服务器,则会出现以下错误:
MongoTimeoutError: Server selection timed out after 30000 ms
You can configure the timeout using the 您可以使用serverSelectionTimeoutMS
option to mongoose.connect()
:serverSelectionTimeoutMS
选项将超时配置为mongoose.connect()
:
mongoose.connect(uri, {
serverSelectionTimeoutMS: 5000 // Timeout after 5s instead of 30s5秒后超时,而不是30秒后超时
});
A MongoTimeoutError
has a reason
property that explains why server selection timed out. MongoTimeoutError
有一个reason
属性,用于解释服务器选择超时的原因。For example, if you're connecting to a standalone server with an incorrect password, 例如,如果您使用不正确的密码连接到独立服务器,reason
will contain an "Authentication failed" error.reason
将包含“身份验证失败”错误。
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. MongoDB副本集依赖于能够可靠地计算出每个成员的域名。On Linux and OSX, the MongoDB server uses the output of the 在Linux和OSX上,MongoDB服务器使用hostname
command to figure out the domain name to report to the replica set. hostname
命令的输出来计算要报告给复制集的域名。This can cause confusing errors if you're connecting to a remote MongoDB replica set running on a machine that reports its 如果您连接到远程MongoDB复制集,该复制集运行在将hostname
as localhost
:hostname
报告为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.如果`rs.conf()`报告一个副本集成员的主机名为`localhost`,即使连接字符串不包括`localhost`,也会出现此错误。
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. mongo
shell连接到副本集,然后运行rs.conf()
命令来检查每个副本集成员的主机名。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. MongooseServerSelectionError
的reason.servers
属性,以查看MongoDB节点驱动程序认为副本集的状态是什么。The reason.servers
property contains a map of server descriptions.reason.servers
属性包含服务器描述的映射。
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多mongos支持
You can also connect to multiple mongos instances for high availability in a sharded cluster. 您还可以连接到多个mongos
实例,以在分片集群中实现高可用性。You do not need to pass any special options to connect to multiple mongos in mongoose 5.x.使用mongoose 5.x 不需要传递任何特殊选项即可连接到多个mongos。
// Connect to 2 mongos servers连接到2台mongos服务器
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的默认连接连接到MongoDB。Mongoose creates a default connection when you call 当您调用mongoose.connect()
. You can access the default connection using mongoose.connection
.mongoose.connect()
时,Mongoose会创建一个默认连接。您可以使用mongoose.connection
访问默认连接。
You may need multiple connections to MongoDB for several reasons. One reason is if you have multiple databases or multiple MongoDB clusters. 由于多种原因,您可能需要多次连接到MongoDB。其中一个原因是,如果您有多个数据库或多个MongoDB集群。Another reason is to work around slow trains. The 另一个原因是在慢火车周围工作。mongoose.createConnection()
function takes the same arguments as mongoose.connect()
and returns a new connection.mongoose.createConnection()
函数采用与mongoose.connect()
相同的参数,并返回一个新的连接。
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.因为如果您导出如下所示的模型,那么该模型的作用域将是Mongoose的默认连接。
// 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.另一种选择是用依赖性注入器或另一种控制反转(IOC)模式来注册连接。
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. mongoose.connect
还是mongoose.createConnection
创建的,都由一个内部可配置的连接池支持,默认最大大小为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.现在我们已经介绍了连接,让我们来看看模型。