> For the complete documentation index, see [llms.txt](https://mongoose.shujuwajue.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mongoose.shujuwajue.com/guide/connections.md).

# 连接（connections）

> 原文：[Connections](http://mongoosejs.com/docs/connections.html)\
> 翻译：小虾米（QQ:509129）

## Connections

我们可以通过利用`mongoose.connect()`方法连接MongoDB 。

```javascript
mongoose.connect('mongodb://localhost/myapp');
```

这是最需要的在连接 myapp数据库运行在默认端口（27017）上。如果本地连接失败，然后尝试用127.0.0.1不是localhost。有时可能会出现问题，当本地主机名已更改。

我们还可以视你的环境而定在URI指定几个参数：

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

查看 [mongodb connection string spec](http://docs.mongodb.org/manual/reference/connection-string/) 了解更多。

### 选项

该连接方法还接受一个选项对象，该对象将被传递给底层驱动程序。这里包含的所有选项优先于连接字符串中传递的选项。

```javascript
mongoose.connect(uri, options);
```

以下是可用的选项键：

* db             - passed to the [underlying driver's db instance](http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html)
* server         - passed to the [underlying driver's server instance(s)](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html)
* replset        - passed to the [underlying driver's ReplSet instance](http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html)
* user           - username for authentication (if not specified in uri)
* pass           - password for authentication (if not specified in uri)
* auth           - options for authentication
* mongos         - passed to the [underlying driver's mongos options](http://mongodb.github.io/node-mongodb-native/2.1/api/Mongos.html)
* promiseLibrary - sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html)

例子：

```javascript
var options = {
  db: { native_parser: true },
  server: { poolSize: 5 },
  replset: { rs_name: 'myReplicaSetName' },
  user: 'myUserName',
  pass: 'myPassword'
}
mongoose.connect(uri, options);
```

**注意：** 服务器选项auto\_reconnect默认为真的可以重写。数据库选项`forceserverobjectid`设置为false将不能被重写。

有关可用选项的更多信息，见[driver](https://github.com/mongodb/node-mongodb-native)。

注意：如果auto\_reconnect设置成on，mongoose会放弃试图恢复一定数量的失败后。设置[`server.reconnectTries`和`server.reconnectInterval options`选项](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html)增加mongoose尝试重新连接的次数。

```javascript
// Good way to make sure mongoose never stops trying to reconnect
mongoose.connect(uri, { server: { reconnectTries: Number.MAX_VALUE } });
```

### 连接字符串选项

mongoose支持以下的连接字符串选项。

* [ssl](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html)
* [poolSize](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html)
* [autoReconnect](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html)
* [socketTimeoutMS](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html)
* [connectTimeoutMS](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html)
* [authSource](http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html)
* [retries](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html)
* [reconnectWait](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html)
* [rs\_name](http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html)
* [replicaSet](http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html)
* [nativeParser](http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html)
* [w](http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html)
* [journal](http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html)
* [wtimeoutMS](http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html)
* [readPreference](http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html)
* [readPreferenceTags](http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html)
* [sslValidate](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html)

### 关于keepAlive

> 对于长时间运行的应用程序，它往往是谨慎开启keepAlive数毫秒。没有它，在一段时间后，你可能会开始看到“连接关闭”的错误，似乎没有理由。如果是这样的话，读了这些之后，你可能会决定启用KeepAlive：

```javascript
options.server.socketOptions = options.replset.socketOptions = { keepAlive: 120 };
mongoose.connect(uri, options);
```

### 复制集连接

用同样方法连接到一个复制集但是通过逗号分隔uris的列表。

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

### 多mongos的支持

高可用性在多mongoss情况下也支持。通过你的mongos实例的连接字符串和设置mongos选项为true：

```javascript
mongoose.connect('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);
```

### 多个连接

到目前为止，我们已经看到了如何连接到使用Mongoose默认连接MongoDB。有时我们可能需要多个连接到Mongo，各有不同的读/写设置，或者只是不同的数据库为例。在这些情况下，我们可以利用`mongoose.createConnection()`接受所有已经讨论的争论并返回你一个新的连接。

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

此连接对象，然后用于创建和检索模型。模型总是局限于单个连接。

### 连接池

每个连接，使用`mongoose.connect`或`mongoose.createconnection`创造所有的内部配置连接池的默认大小为5的支持 。使用您的连接选项调整池大小：

```javascript
// single server
var uri = 'mongodb://localhost/test';
mongoose.createConnection(uri, { server: { poolSize: 4 }});

// for a replica set
mongoose.createConnection(uri, { replset: { poolSize: 4 }});

// passing the option in the URI works with single or replica sets
var uri = 'mongodb://localhost/test?poolSize=4';
mongoose.createConnection(uri);
```

### 下一步

现在我们已经掌握了connections，让我们看看我们如何能将我们的功能的碎片变成可重用的并共享[插件](http://mongoosejs.com/docs/plugins.html)。
