Class MongoClient

The MongoClient class is a class that allows for making Connections to MongoDB.MongoClient类是一个允许连接MongoDB的类。

Remarks

The programmatically provided options take precedence over the URI options.以编程方式提供的选项优先于URI选项。

Example

import { MongoClient } from 'mongodb';

// Enable command monitoring for debugging启用调试命令监视
const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true });

client.on('commandStarted', started => console.log(started));
client.db().collection('pets');
await client.insertOne({ name: 'spot', kind: 'dog' });

Hierarchy层级

Constructors

Properties

captureRejectionSymbol: typeof captureRejectionSymbol
captureRejections: boolean

Sets or gets the default captureRejection value for all emitters.设置或获取所有发射器的默认captureRejection值。

defaultMaxListeners: number
errorMonitor: typeof errorMonitor

This symbol shall be used to install a listener for only monitoring 'error' events. Listeners installed using this symbol are called before the regular 'error' listeners are called.此符号应用于安装仅用于监视'error'事件的侦听器。在调用常规'error'侦听器之前,将调用使用此符号安装的侦听器。

Installing a listener using this symbol does not change the behavior once an 'error' event is emitted, therefore the process will still crash if no regular 'error' listener is installed.一旦发出'error'事件,使用此符号安装侦听器不会改变行为,因此,如果未安装常规的'error'侦听器,进程仍将崩溃。

Accessors

Methods

  • Close the client and its underlying connections关闭客户端及其基础连接

    Parameters

    • force: boolean = false

      Force close, emitting no events强制关闭,不发出任何事件

    Returns Promise<void>

  • Create a new Db instance sharing the current socket connections.创建一个共享当前套接字连接的新Db实例。

    Parameters

    • Optional dbName: string

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

    • Optional options: DbOptions

      Optional settings for Db constructionDb构造的可选设置

    Returns Db

  • Type Parameters

    • EventKey extends "error" | "timeout" | "close" | "open" | "serverOpening" | "serverClosed" | "serverDescriptionChanged" | "topologyOpening" | "topologyClosed" | "topologyDescriptionChanged" | "connectionPoolCreated" | "connectionPoolClosed" | "connectionPoolCleared" | "connectionPoolReady" | "connectionCreated" | "connectionReady" | "connectionClosed" | "connectionCheckOutStarted" | "connectionCheckOutFailed" | "connectionCheckedOut" | "connectionCheckedIn" | "commandStarted" | "commandSucceeded" | "commandFailed" | "serverHeartbeatStarted" | "serverHeartbeatSucceeded" | "serverHeartbeatFailed"

    Parameters

    Returns boolean

  • Type Parameters

    • EventKey extends "error" | "timeout" | "close" | "open" | "serverOpening" | "serverClosed" | "serverDescriptionChanged" | "topologyOpening" | "topologyClosed" | "topologyDescriptionChanged" | "connectionPoolCreated" | "connectionPoolClosed" | "connectionPoolCleared" | "connectionPoolReady" | "connectionCreated" | "connectionReady" | "connectionClosed" | "connectionCheckOutStarted" | "connectionCheckOutFailed" | "connectionCheckedOut" | "connectionCheckedIn" | "commandStarted" | "commandSucceeded" | "commandFailed" | "serverHeartbeatStarted" | "serverHeartbeatSucceeded" | "serverHeartbeatFailed"

    Parameters

    • type: string | symbol | EventKey

    Returns number

  • Type Parameters

    • EventKey extends "error" | "timeout" | "close" | "open" | "serverOpening" | "serverClosed" | "serverDescriptionChanged" | "topologyOpening" | "topologyClosed" | "topologyDescriptionChanged" | "connectionPoolCreated" | "connectionPoolClosed" | "connectionPoolCleared" | "connectionPoolReady" | "connectionCreated" | "connectionReady" | "connectionClosed" | "connectionCheckOutStarted" | "connectionCheckOutFailed" | "connectionCheckedOut" | "connectionCheckedIn" | "commandStarted" | "commandSucceeded" | "commandFailed" | "serverHeartbeatStarted" | "serverHeartbeatSucceeded" | "serverHeartbeatFailed"

    Parameters

    • event: string | symbol | EventKey

    Returns MongoClientEvents[EventKey][]

  • Type Parameters

    • EventKey extends "error" | "timeout" | "close" | "open" | "serverOpening" | "serverClosed" | "serverDescriptionChanged" | "topologyOpening" | "topologyClosed" | "topologyDescriptionChanged" | "connectionPoolCreated" | "connectionPoolClosed" | "connectionPoolCleared" | "connectionPoolReady" | "connectionCreated" | "connectionReady" | "connectionClosed" | "connectionCheckOutStarted" | "connectionCheckOutFailed" | "connectionCheckedOut" | "connectionCheckedIn" | "commandStarted" | "commandSucceeded" | "commandFailed" | "serverHeartbeatStarted" | "serverHeartbeatSucceeded" | "serverHeartbeatFailed"

    Parameters

    Returns MongoClient

  • Parameters

    • event: CommonEvents
    • listener: ((eventName, listener) => void)
        • (eventName, listener): void
        • Parameters

          Returns void

    Returns MongoClient

  • Parameters

    Returns MongoClient

  • Type Parameters

    • EventKey extends "error" | "timeout" | "close" | "open" | "serverOpening" | "serverClosed" | "serverDescriptionChanged" | "topologyOpening" | "topologyClosed" | "topologyDescriptionChanged" | "connectionPoolCreated" | "connectionPoolClosed" | "connectionPoolCleared" | "connectionPoolReady" | "connectionCreated" | "connectionReady" | "connectionClosed" | "connectionCheckOutStarted" | "connectionCheckOutFailed" | "connectionCheckedOut" | "connectionCheckedIn" | "commandStarted" | "commandSucceeded" | "commandFailed" | "serverHeartbeatStarted" | "serverHeartbeatSucceeded" | "serverHeartbeatFailed"

    Parameters

    Returns MongoClient

  • Parameters

    • event: CommonEvents
    • listener: ((eventName, listener) => void)
        • (eventName, listener): void
        • Parameters

          Returns void

    Returns MongoClient

  • Parameters

    Returns MongoClient

  • Type Parameters

    • EventKey extends "error" | "timeout" | "close" | "open" | "serverOpening" | "serverClosed" | "serverDescriptionChanged" | "topologyOpening" | "topologyClosed" | "topologyDescriptionChanged" | "connectionPoolCreated" | "connectionPoolClosed" | "connectionPoolCleared" | "connectionPoolReady" | "connectionCreated" | "connectionReady" | "connectionClosed" | "connectionCheckOutStarted" | "connectionCheckOutFailed" | "connectionCheckedOut" | "connectionCheckedIn" | "commandStarted" | "commandSucceeded" | "commandFailed" | "serverHeartbeatStarted" | "serverHeartbeatSucceeded" | "serverHeartbeatFailed"

    Parameters

    Returns MongoClient

  • Parameters

    • event: CommonEvents
    • listener: ((eventName, listener) => void)
        • (eventName, listener): void
        • Parameters

          Returns void

    Returns MongoClient

  • Parameters

    Returns MongoClient

  • Type Parameters

    • EventKey extends "error" | "timeout" | "close" | "open" | "serverOpening" | "serverClosed" | "serverDescriptionChanged" | "topologyOpening" | "topologyClosed" | "topologyDescriptionChanged" | "connectionPoolCreated" | "connectionPoolClosed" | "connectionPoolCleared" | "connectionPoolReady" | "connectionCreated" | "connectionReady" | "connectionClosed" | "connectionCheckOutStarted" | "connectionCheckOutFailed" | "connectionCheckedOut" | "connectionCheckedIn" | "commandStarted" | "commandSucceeded" | "commandFailed" | "serverHeartbeatStarted" | "serverHeartbeatSucceeded" | "serverHeartbeatFailed"

    Parameters

    • event: string | symbol | EventKey

    Returns MongoClientEvents[EventKey][]

  • Type Parameters

    • EventKey extends "error" | "timeout" | "close" | "open" | "serverOpening" | "serverClosed" | "serverDescriptionChanged" | "topologyOpening" | "topologyClosed" | "topologyDescriptionChanged" | "connectionPoolCreated" | "connectionPoolClosed" | "connectionPoolCleared" | "connectionPoolReady" | "connectionCreated" | "connectionReady" | "connectionClosed" | "connectionCheckOutStarted" | "connectionCheckOutFailed" | "connectionCheckedOut" | "connectionCheckedIn" | "commandStarted" | "commandSucceeded" | "commandFailed" | "serverHeartbeatStarted" | "serverHeartbeatSucceeded" | "serverHeartbeatFailed"

    Parameters

    • Optional event: string | symbol | EventKey

    Returns MongoClient

  • Creates a new ClientSession. 创建新的ClientSessionWhen using the returned session in an operation a corresponding ServerSession will be created.在操作中使用返回的会话时,将创建相应的ServerSession

    Parameters

    Returns ClientSession

    Remarks

    A ClientSession instance may only be passed to operations being performed on the same MongoClient it was started from.ClientSession实例只能传递给在启动它的同一MongoClient上执行的操作。

  • Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. 创建一个新的变更流,监视此群集中的新变更(插入、更新、替换、删除和无效)。Will ignore all changes to system collections, as well as the local, admin, and config databases.将忽略对系统集合以及本地、管理和配置数据库的所有更改。

    Type Parameters

    • TSchema extends Document = Document

      Type of the data being detected by the change stream变更流检测到的数据类型

    • TChange extends Document = ChangeStreamDocument<TSchema>

      Type of the whole change stream document emitted发出的整个变更流文档的类型

    Parameters

    • pipeline: Document[] = []

      An array of pipeline stages through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.一组管道阶段,通过这些阶段传递更改流文档。这允许筛选(使用$match)和操作变更流文档。

    • options: ChangeStreamOptions = {}

      Optional settings for the command命令的可选设置

    Returns ChangeStream<TSchema, TChange>

    Remarks

    watch() accepts two generic arguments for distinct use cases:watch()为不同的用例接受两个泛型参数:

    • The first is to provide the schema that may be defined for all the data within the current cluster第一个是提供可以为当前集群中的所有数据定义的模式
    • The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument第二种是完全覆盖变更流文档的形状,如果没有提供,则类型将默认为第一个参数的ChangeStreamDocument
  • A convenience method for creating and handling the clean up of a ClientSession.创建和处理ClientSession清理的一种方便方法。The session will always be ended when the executor finishes.会话将始终在executor完成时结束。

    Type Parameters

    • T = any

    Parameters

    • executor: WithSessionCallback<T>

      An executor function that all operations using the provided session must be invoked in必须在中调用使用所提供会话的所有操作的执行器函数

    Returns Promise<T>

  • Type Parameters

    • T = any

    Parameters

    Returns Promise<T>

  • Returns a copy of the array of listeners for the event named eventName.返回名为eventName的事件的侦听器数组的副本。

    For EventEmitters this behaves exactly the same as calling .listeners on the emitter.对于EventEmitter,其行为与在发射器上调用侦听器完全相同。

    For EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.对于EventTarget,这是获取事件目标的事件侦听器的唯一方法。这对于调试和诊断非常有用。

    import { getEventListeners, EventEmitter } from 'node:events';

    {
    const ee = new EventEmitter();
    const listener = () => console.log('Events are fun');
    ee.on('foo', listener);
    console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
    }
    {
    const et = new EventTarget();
    const listener = () => console.log('Events are fun');
    et.addEventListener('foo', listener);
    console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
    }

    Parameters

    • emitter: EventEmitter | _DOMEventTarget
    • name: string | symbol

    Returns Function[]

    Since

    v15.2.0, v14.17.0

  • A class method that returns the number of listeners for the given eventName registered on the given emitter.一个类方法,用于返回在给定emitter上注册的给定eventName的侦听器数。

    import { EventEmitter, listenerCount } from 'node:events';

    const myEmitter = new EventEmitter();
    myEmitter.on('event', () => {});
    myEmitter.on('event', () => {});
    console.log(listenerCount(myEmitter, 'event'));
    // Prints: 2

    Parameters

    • emitter: EventEmitter

      The emitter to query要查询的发射器

    • eventName: string | symbol

      The event name事件名称

    Returns number

    Since

    v0.9.12

    Deprecated

    Since v3.2.0 - Use listenerCount instead.由于v3.2.0-请改用listenerCount

  • import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo')) {
    // The execution of this inner block is synchronous and it processes one event at a time (even with await). 这个内部块的执行是同步的,它一次处理一个事件(即使有等待)。
    // Do not use if concurrent execution is required.如果需要并发执行,请不要使用。
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here

    Returns an AsyncIterator that iterates eventName events. 返回一个迭代eventName事件的AsyncIteratorIt will throw if the EventEmitter emits 'error'. 如果EventEmitter发出'error',它将抛出。It removes all listeners when exiting the loop. 它在退出循环时删除所有侦听器。The value returned by each iteration is an array composed of the emitted event arguments.每次迭代返回的value是一个由发出的事件参数组成的数组。

    An AbortSignal can be used to cancel waiting on events:AbortSignal可用于取消等待事件:

    import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ac = new AbortController();

    (async () => {
    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo', { signal: ac.signal })) {
    // The execution of this inner block is synchronous and it processes one event at a time (even with await). 这个内部块的执行是同步的,它一次处理一个事件(即使有等待)。
    // Do not use if concurrent execution is required.如果需要并发执行,请不要使用。
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here
    })();

    process.nextTick(() => ac.abort());

    Parameters

    • emitter: EventEmitter
    • eventName: string

      The name of the event being listened for正在侦听的事件的名称

    • Optional options: StaticEventEmitterOptions

    Returns AsyncIterableIterator<any>

    that iterates eventName events emitted by the emitter迭代emitter发出的eventName事件

    Since

    v13.6.0, v12.16.0

  • Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting.创建一个Promise,该Promise在EventEmitter发出给定事件时实现,或者如果EventEmitter在等待时发出'error'则被拒绝。 The Promise will resolve with an array of all the arguments emitted to the given event.Promise将通过向给定事件发出的所有参数的数组进行解析。

    This method is intentionally generic and works with the web platform EventTarget interface, which has no special 'error' event semantics and does not listen to the 'error' event.此方法是有意通用的,可与web平台EventTarget接口配合使用,该接口没有特殊的'error'事件语义,也不侦听'error'消息。

    import { once, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    process.nextTick(() => {
    ee.emit('myevent', 42);
    });

    const [value] = await once(ee, 'myevent');
    console.log(value);

    const err = new Error('kaboom');
    process.nextTick(() => {
    ee.emit('error', err);
    });

    try {
    await once(ee, 'myevent');
    } catch (err) {
    console.error('error happened', err);
    }

    The special handling of the 'error' event is only used when events.once() is used to wait for another event. 'error'事件的特殊处理仅在events.once()用于等待另一个事件时使用。If events.once() is used to wait for the 'error' event itself, then it is treated as any other kind of event without special handling:如果events.once()用于等待'error'事件本身,那么它将被视为任何其他类型的事件,而无需特殊处理:

    import { EventEmitter, once } from 'node:events';

    const ee = new EventEmitter();

    once(ee, 'error')
    .then(([err]) => console.log('ok', err.message))
    .catch((err) => console.error('error', err.message));

    ee.emit('error', new Error('boom'));

    // Prints: ok boom

    An AbortSignal can be used to cancel waiting for the event:AbortSignal可用于取消等待事件:

    import { EventEmitter, once } from 'node:events';

    const ee = new EventEmitter();
    const ac = new AbortController();

    async function foo(emitter, event, signal) {
    try {
    await once(emitter, event, { signal });
    console.log('event emitted!');
    } catch (error) {
    if (error.name === 'AbortError') {
    console.error('Waiting for the event was canceled!');
    } else {
    console.error('There was an error', error.message);
    }
    }
    }

    foo(ee, 'foo', ac.signal);
    ac.abort(); // Abort waiting for the event
    ee.emit('foo'); // Prints: Waiting for the event was canceled!

    Parameters

    • emitter: _NodeEventTarget
    • eventName: string | symbol
    • Optional options: StaticEventEmitterOptions

    Returns Promise<any[]>

    Since

    v11.13.0, v10.16.0

  • Parameters

    • emitter: _DOMEventTarget
    • eventName: string
    • Optional options: StaticEventEmitterOptions

    Returns Promise<any[]>

  • import { setMaxListeners, EventEmitter } from 'node:events';

    const target = new EventTarget();
    const emitter = new EventEmitter();

    setMaxListeners(5, target, emitter);

    Parameters

    • Optional n: number

      A non-negative number. The maximum number of listeners per EventTarget event.一个非负数。每个EventTarget事件的最大侦听器数。

    • Rest ...eventTargets: (EventEmitter | _DOMEventTarget)[]

    Returns void

    Since

    v15.4.0

Generated using TypeDoc