Connection


Connection()

Parameters:参数:
  • base «Mongoose» a mongoose instance

Inherits:继承:

Connection constructor连接构造函数

For practical reasons, a Connection equals a Db.出于实际原因,Connection等于Db。


Connection.prototype.asPromise()

Returns:返回:
  • «Promise»

Returns a promise that resolves when this connection successfully connects to MongoDB, or rejects if this connection failed to connect.返回一个promise,该promise在该连接成功连接到MongoDB时解析,或者在该连接连接失败时拒绝。

Example:示例:

const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/test').
asPromise();
conn.readyState; // 1, means Mongoose is connected

Connection.prototype.client

Type:类型:
  • «property»

The MongoClient instance this connection uses to talk to MongoDB. 此连接用于与MongoDB对话的MongoClient实例。Mongoose automatically sets this property when the connection is opened.当连接打开时,Mongoose会自动设置此属性。


Connection.prototype.close()

Parameters:参数:
  • [force] «Boolean» optional

Returns:返回:
  • «Promise»

Closes the connection关闭连接


Connection.prototype.collection()

Parameters:参数:
  • name «String» of the collection集合的«String»

  • [options] «Object» optional collection options可选集合选项

Returns:返回:
  • «Collection» collection instance

Retrieves a collection, creating it if not cached.检索集合,如果未缓存则创建该集合。

Not typically needed by applications. Just talk to your collection through your model.应用程序通常不需要。只需通过您的模型与您的集合对话。


Connection.prototype.collections

Type:类型:
  • «property»

A hash of the collections associated with this connection与此连接关联的集合的哈希


Connection.prototype.config

Type:类型:
  • «property»

A hash of the global options that are associated with this connection与此连接关联的全局选项的哈希


Connection.prototype.createCollection()

Parameters:参数:
  • collection «string» The collection to create要创建的集合

  • [options] «Object» see MongoDB driver docs

Returns:返回:
  • «Promise»

Helper for createCollection(). Will explicitly create the given collection with specified options. Used to create capped collections and views from mongoose.

Options are passed down without modification to the MongoDB driver's createCollection() function


Connection.prototype.db

Type:类型:
  • «property»

The mongodb.Db instance, set when the connection is openedmongodbDb实例,在打开连接时设置


Connection.prototype.deleteModel()

Parameters:参数:
  • name «String|RegExp» if string, the name of the model to remove. 如果是字符串,要删除的模型的名称。If regexp, removes all models whose name matches the regexp.如果是regexp,则删除名称与regexp匹配的所有模型。

Returns:返回:
  • «Connection» this

Removes the model named name from this connection, if it exists. 从该连接中删除命名的模型name(如果存在)。You can use this function to clean up any models you created in your tests to prevent OverwriteModelErrors.您可以使用此函数来清除您在测试中创建的任何模型,以防止OverwriteModelErrors。

Example:示例:

conn.model('User', new Schema({ name: String }));
console.log(conn.model('User')); // Model object
conn.deleteModel('User');
console.log(conn.model('User')); // undefined

// Usually useful in a Mocha `afterEach()` hook
afterEach(function() {
conn.deleteModel(/.+/); // Delete every model
});

Connection.prototype.destroy()

Parameters:参数:
  • [force] «Boolean»

Destory the connection (not just a alias of .close)


Connection.prototype.dropCollection()

Parameters:参数:
  • collection «string» The collection to delete要删除的集合

Returns:返回:
  • «Promise»

Helper for dropCollection(). dropCollection()的帮助程序。Will delete the given collection, including all documents and indexes.将删除给定的集合,包括所有文档和索引。


Connection.prototype.dropDatabase()

Returns:返回:
  • «Promise»

Helper for dropDatabase(). dropDatabase()的帮助程序。Deletes the given database, including all collections, documents, and indexes.删除给定的数据库,包括所有集合、文档和索引。

Example:示例:

const conn = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
// Deletes the entire 'mydb' database
await conn.dropDatabase();

Connection.prototype.get()

Parameters:参数:
  • key «String»

Gets the value of the option key. Equivalent to conn.options[key]

Example:示例:

conn.get('test'); // returns the 'test' value

Connection.prototype.getClient()

Returns:返回:
  • «MongoClient»

Returns the MongoDB driver MongoClient instance that this connection uses to talk to MongoDB.

Example:示例:

const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/test').
asPromise();

conn.getClient(); // MongoClient { ... }

Connection.prototype.host

Type:类型:
  • «property»

The host name portion of the URI. URI的主机名部分。If multiple hosts, such as a replica set, this will contain the first host name in the URI如果有多个主机,例如一个复制集,则这将包含URI中的第一个主机名

Example:示例:

mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').host; // "127.0.0.1"

Connection.prototype.id

Type:类型:
  • «property»

A number identifier for this connection. 此连接的数字标识符。Used for debugging when you have multiple connections.用于在具有多个连接时进行调试。

Example:示例:

// The default connection has `id = 0`
mongoose.connection.id; // 0

// If you create a new connection, Mongoose increments id
const conn = mongoose.createConnection();
conn.id; // 1

Connection.prototype.model()

Parameters:参数:
  • name «String|Function» the model name or class extending Model

  • [schema] «Schema» a schema. necessary when defining a model定义模型时需要

  • [collection] «String» name of mongodb collection (optional) if not given it will be induced from model name

  • [options] «Object»
    • [options.overwriteModels=false] «Boolean» If true, overwrite existing models with the same name to avoid OverwriteModelError如果为true,则用相同的名称覆盖现有模型以避免OverwriteModelError

Returns:返回:
  • «Model» The compiled model编译后的模型
See:

Defines or retrieves a model.定义或检索模型。

const mongoose = require('mongoose');
const db = mongoose.createConnection(..);
db.model('Venue', new Schema(..));
const Ticket = db.model('Ticket', new Schema(..));
const Venue = db.model('Venue');

When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. 此方法将名称复数化。If you don't like this behavior, either pass a collection name or set your schemas collection name option.如果您不喜欢这种行为,请传递集合名称或设置架构集合名称选项。

Example:示例:

const schema = new Schema({ name: String }, { collection: 'actor' });

// or

schema.set('collection', 'actor');

// or

const collectionName = 'actor'
const M = conn.model('Actor', schema, collectionName)

Connection.prototype.modelNames()

Returns:返回:
  • «Array[String]»

Returns an array of model names created on this connection.返回在此连接上创建的模型名称的数组。


Connection.prototype.models

Type:类型:
  • «property»

A POJO containing a map from model names to models. 一个POJO,包含从模型名称到模型的映射。Contains all models that have been added to this connection using Connection#model().包含已使用Connection#model()添加到此连接的所有模型。

Example:示例:

const conn = mongoose.createConnection();
const Test = conn.model('Test', mongoose.Schema({ name: String }));

Object.keys(conn.models).length; // 1
conn.models.Test === Test; // true

Connection.prototype.name

Type:类型:
  • «property»

The name of the database this connection points to.此连接指向的数据库的名称。

Example:示例:

mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').name; // "mydb"

Connection.prototype.openUri()

Parameters:参数:
  • uri «String» The URI to connect with.要连接的URI。

  • [options] «Object» Passed on to MongoClient.connect

    • [options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to disable buffering on all models associated with this connection.

    • [options.bufferTimeoutMS=10000] «Number» Mongoose specific option. Mongoose特定选项。If bufferCommands is true, Mongoose will throw an error after bufferTimeoutMS if the operation is still buffered.如果bufferCommandstrue,那么如果操作仍处于缓冲状态,Mongoose将在bufferTimeoutMS之后抛出错误。

    • [options.dbName] «String» The name of the database we want to use. 我们要使用的数据库的名称。If not provided, use database name from connection string.如果未提供,请使用连接字符串中的数据库名称。

    • [options.user] «String» username for authentication, equivalent to options.auth.user. 用于身份验证的用户名,相当于options.auth.userMaintained for backwards compatibility.保持向后兼容性。

    • [options.pass] «String» password for authentication, equivalent to options.auth.password. 用于身份验证的密码,相当于options.auth.passwordMaintained for backwards compatibility.保持向后兼容性。

    • [options.maxPoolSize=100] «Number» The maximum number of sockets the MongoDB driver will keep open for this connection. MongoDB驱动程序将为此连接保持打开的最大套接字数。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. 请记住,MongoDB一次只允许每个套接字进行一次操作,因此如果您发现有一些较慢的查询阻碍了较快的查询的进行,则可能需要增加这一操作。See Slow Trains in MongoDB and Node.js.请参阅MongoDB和Node.js中的慢速列车

    • [options.minPoolSize=0] «Number» The minimum number of sockets the MongoDB driver will keep open for this connection. MongoDB驱动程序将为该连接保持打开的最小套接字数。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. 请记住,MongoDB一次只允许每个套接字进行一次操作,因此如果您发现有一些较慢的查询阻碍了较快的查询的进行,则可能需要增加这一操作。See Slow Trains in MongoDB and Node.js.请参阅MongoDB和Node.js中的慢速列车

    • [options.serverSelectionTimeoutMS] «Number» If useUnifiedTopology = true, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for serverSelectionTimeoutMS milliseconds before erroring out. If not set, the MongoDB driver defaults to using 30000 (30 seconds).如果未设置,MongoDB驱动程序默认使用30000(30秒)。

    • [options.heartbeatFrequencyMS] «Number» If useUnifiedTopology = true, 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.

    • [options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.

    • [options.connectTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity during initial connection. Defaults to 30000. This option is passed transparently to Node.js' socket#setTimeout() function.

    • [options.socketTimeoutMS=30000] «Number» 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.

    • [options.family=0] «Number» Passed transparently to Node.js' dns.lookup() function. May be either 0, 4, or 6. 4means use IPv4 only,6means use IPv6 only,0` means try both.

    • [options.autoCreate=false] «Boolean» Set to true to make Mongoose automatically call createCollection() on every model created on this connection.

Opens the connection with a URI using MongoClient.connect().使用MongoClient.connect()打开带有URI的连接。


Connection.prototype.pass

Type:类型:
  • «property»

The password specified in the URIURI中指定的密码

Example:示例:

mongoose.createConnection('mongodb://val:psw@127.0.0.1:27017/mydb').pass; // "psw"

Connection.prototype.plugin()

Parameters:参数:
  • fn «Function» plugin callback

  • [opts] «Object» optional options

Returns:返回:
  • «Connection» this
See:

Declares a plugin executed on all schemas you pass to conn.model()声明在传递给conn.model()的所有模式上执行的插件

Equivalent to calling .plugin(fn) on each schema you create.相当于在您创建的每个模式上调用.plugin(fn)

Example:示例:

const db = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
db.plugin(() => console.log('Applied'));
db.plugins.length; // 1

db.model('Test', new Schema({})); // Prints "Applied"

Connection.prototype.plugins

Type:类型:
  • «property»

The plugins that will be applied to all models created on this connection.将应用于在此连接上创建的所有模型的插件。

Example:示例:

const db = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
db.plugin(() => console.log('Applied'));
db.plugins.length; // 1

db.model('Test', new Schema({})); // Prints "Applied"

Connection.prototype.port

Type:类型:
  • «property»

The port portion of the URI. If multiple hosts, such as a replica set, this will contain the port from the first host name in the URI.URI的端口部分。如果有多个主机,例如一个复制集,则会包含URI中第一个主机名的端口。

Example:示例:

mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').port; // 27017

Connection.prototype.readyState

Type:类型:
  • «property»

Connection ready state连接就绪状态

  • 0 = disconnected
  • 1 = connected
  • 2 = connecting
  • 3 = disconnecting

Each state change emits its associated event name.每个状态更改都会发出其关联的事件名称。

Example:示例:

conn.on('connected', callback);
conn.on('disconnected', callback);

Connection.prototype.set()

Parameters:参数:
  • key «String»
  • val «Any»

Sets the value of the option key. Equivalent to conn.options[key] = val

Supported options include:

  • maxTimeMS: Set maxTimeMS for all queries on this connection.
  • 'debug': If true, prints the operations mongoose sends to MongoDB to the console. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arugments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callback Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')}).

Example:示例:

conn.set('test', 'foo');
conn.get('test'); // 'foo'
conn.options.test; // 'foo'

Connection.prototype.setClient()

Parameters:参数:
  • client «MongClient» The Client to set to be used.

Returns:返回:
  • «Connection» this

Set the MongoDB driver MongoClient instance that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to reuse it.

Example:示例:

const client = await mongodb.MongoClient.connect('mongodb://127.0.0.1:27017/test');

const conn = mongoose.createConnection().setClient(client);

conn.getClient(); // MongoClient { ... }
conn.readyState; // 1, means 'CONNECTED'

Connection.prototype.startSession()

Parameters:参数:
  • [options] «Object» see the mongodb driver options

    • [options.causalConsistency=true] «Boolean» set to false to disable causal consistency

Returns:返回:
  • «Promise<ClientSession>» promise that resolves to a MongoDB driver ClientSession

Requires MongoDB >= 3.6.0. Starts a MongoDB session for benefits like causal consistency, retryable writes, and transactions.

Example:示例:

const session = await conn.startSession();
let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
await doc.remove();
// `doc` will always be null, even if reading from a replica set
// secondary. Without causal consistency, it is possible to
// get a doc back from the below query if the query reads from a
// secondary that is experiencing replication lag.
doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });

Connection.prototype.syncIndexes()

Parameters:参数:
  • [options] «Object»
    • [options.continueOnError] «Boolean» false by default. If set to true, mongoose will not throw an error if one model syncing failed, and will return an object where the keys are the names of the models, and the values are the results/errors for each model.

Returns:返回:
  • «Promise<Object>» Returns a Promise, when the Promise resolves the value is a list of the dropped indexes.返回Promise,当Promise解析时,该值是一个已删除索引的列表。

Syncs all the indexes for the models registered with this connection.同步使用此连接注册的模型的所有索引。


Connection.prototype.transaction()

Parameters:参数:
  • fn «Function» Function to execute in a transaction要在事务中执行的函数

  • [options] «[object Object]» Optional settings for the transaction事务的可选设置

Returns:返回:
  • «Promise<Any>» promise that is fulfilled if Mongoose successfully committed the transaction, or rejects if the transaction was aborted or if Mongoose failed to commit the transaction. 如果Mongoose成功提交了事务,则承诺将实现;如果事务中止或Mongoose未能提交事务,则拒绝。If fulfilled, the promise resolves to a MongoDB command result.如果实现了,promise将解析为MongoDB命令结果。

Requires MongoDB >= 3.6.0. Executes the wrapped async function in a transaction. 在事务中执行封装的异步函数。Mongoose will commit the transaction if the async function executes successfully and attempt to retry if there was a retriable error.如果异步函数执行成功,Mongoose将提交事务,如果出现可重试的错误,则尝试重试。

Calls the MongoDB driver's session.withTransaction(), but also handles resetting Mongoose document state as shown below.

Example:示例:

const doc = new Person({ name: 'Will Riker' });
await db.transaction(async function setRank(session) {
doc.rank = 'Captain';
await doc.save({ session });
doc.isNew; // false

// Throw an error to abort the transaction
throw new Error('Oops!');
},{ readPreference: 'primary' }).catch(() => {});

// true, `transaction()` reset the document's state because the
// transaction was aborted.
doc.isNew;

Connection.prototype.useDb()

Parameters:参数:
  • name «String» The database name数据库名称

  • [options] «Object»
    • [options.useCache=false] «Boolean» If true, cache results so calling useDb() multiple times with the same name only creates 1 connection object.

    • [options.noListener=false] «Boolean» If true, the connection object will not make the db listen to events on the original connection. See issue #9961.

Returns:返回:
  • «Connection» New Connection Object新建连接对象

Switches to a different database using the same connection pool.使用相同的连接池切换到不同的数据库。

Returns a new connection object, with the new db.返回一个带有新数据库的新连接对象。

Example:示例:

// Connect to `initialdb` first
const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/initialdb').asPromise();

// Creates an un-cached connection to `mydb`
const db = conn.useDb('mydb');
// Creates a cached connection to `mydb2`. All calls to `conn.useDb('mydb2', { useCache: true })` will return the same
// connection instance as opposed to creating a new connection instance
const db2 = conn.useDb('mydb2', { useCache: true });

Connection.prototype.user

Type:类型:
  • «property»

The username specified in the URI

Example:示例:

mongoose.createConnection('mongodb://val:psw@127.0.0.1:27017/mydb').user; // "val"

Connection.prototype.watch()

Parameters:参数:
Returns:返回:
  • «ChangeStream» mongoose-specific change stream wrapper, inherits from EventEmitter

Watches the entire underlying database for changes. Similar to Model.watch().

This function does not trigger any middleware. In particular, it does not trigger aggregate middleware.

The ChangeStream object is an event emitter that emits the following events:

  • 'change': A change occurred, see below example
  • 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow this GitHub issue for updates.
  • 'end': Emitted if the underlying stream is closed
  • 'close': Emitted if the underlying stream is closed

Example:示例:

const User = conn.model('User', new Schema({ name: String }));

const changeStream = conn.watch().on('change', data => console.log(data));

// Triggers a 'change' event on the change stream.
await User.create({ name: 'test' });