Options
All
  • Public
  • Public/Protected
  • All
Menu

Class ClientSession

A class representing a client session on the server表示服务器上客户端会话的类

NOTE: not meant to be instantiated directly.注意:不打算直接实例化。

Hierarchy继承层级

Index索引

Properties属性

clientOptions?: MongoOptions
clusterTime?: ClusterTime
defaultTransactionOptions: TransactionOptions
explicit: boolean
hasEnded: boolean
operationTime?: Timestamp
supports: { causalConsistency: boolean }

Type declaration类型声明

  • causalConsistency: boolean
transaction: Transaction
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. 此符号应用于安装仅用于监视'error'事件的侦听器。Listeners installed using this symbol are called before the regular 'error' listeners are called.使用此符号安装的侦听器在调用常规'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访问器

  • get isPinned(): boolean
  • get loadBalanced(): boolean
  • get snapshotEnabled(): boolean
  • Whether or not this session is configured for snapshot reads是否为快照读取配置此会话

    Returns 返回 boolean

Methods方法

  • Aborts the currently active transaction in this session.中止此会话中当前活动的事务。

    Returns 返回 Promise<Document>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession将ClientSession的clusterTime提前到另一个ClientSessions的提供的clustrTime

    Parameters参数

    • clusterTime: ClusterTime

      the $clusterTime returned by the server from another session in the form of a document containing the BSON.Timestamp clusterTime and signature服务器从另一个会话以包含BSON.Timestamp clusterTime和签名的文档形式返回的$clusterName

    Returns 返回 void

  • advanceOperationTime(operationTime: Timestamp): void
  • Advances the operationTime for a ClientSession.提前ClientSession的操作时间。

    Parameters参数

    • operationTime: Timestamp

      the BSON.Timestamp of the operation type it is desired to advance to希望前进到的操作类型的BSON.Timestamp

    Returns 返回 void

  • Commits the currently active transaction in this session.提交此会话中当前活动的事务。

    Returns 返回 Promise<Document>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • emit<EventKey>(event: symbol | EventKey, ...args: Parameters<ClientSessionEvents[EventKey]>): boolean
  • Ends this session on the server在服务器上结束此会话

    Returns 返回 Promise<void>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<void>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Used to determine if this session equals another用于确定此会话是否等于另一个会话

    Parameters参数

    • session: ClientSession

      The session to compare to要比较的会话

    Returns 返回 boolean

  • eventNames(): string[]
  • getMaxListeners(): number
  • inTransaction(): boolean
  • Returns 返回 boolean

    whether this session is currently in a transaction or not该会话当前是否处于事务中

  • incrementTransactionNumber(): void
  • Increment the transaction number on the internal ServerSession增加内部ServerSession上的事务编号

    privateremarks

    This helper increments a value stored on the client session that will be added to the serverSession's txnNumber upon applying it to a command. 此助手将增加存储在客户端会话上的值,该值将在应用于命令时添加到serverSession的txnNumber。This is because the serverSession is lazily acquired after a connection is obtained这是因为在获得连接后,服务器会话被延迟获取

    Returns 返回 void

  • listenerCount<EventKey>(type: string | symbol | EventKey): number
  • removeAllListeners<EventKey>(event?: string | symbol | EventKey): ClientSession
  • Starts a new transaction with the given options.

    Parameters参数

    Returns 返回 void

  • toBSON(): never
  • This is here to ensure that ClientSession is never serialized to BSON.这是为了确保ClientSession永远不会序列化到BSON。

    Returns 返回 never

  • Runs a provided callback within a transaction, retrying either the commitTransaction operation or entire transaction as needed (and when the error permits) to better ensure that the transaction can complete successfully.在事务中运行提供的回调,根据需要(在错误允许的情况下)重试commitTransaction操作或整个事务,以更好地确保事务能够成功完成。

    IMPORTANT: This method requires the user to return a Promise, and await all operations. 此方法要求用户返回Promise,并await所有操作。Any callbacks that do not return a Promise will result in undefined behavior.任何不返回Promise的回调都将导致未定义的行为。

    remarks

    This function:此功能:

    • Will return the command response from the final commitTransaction if every operation is successful (can be used as a truthy object)如果每个操作都成功,将从最终commitTransaction返回命令响应(可以用作真实对象)
    • Will return undefined if the transaction is explicitly aborted with await session.abortTransaction()如果事务用await session.abortTransaction()显式中止,将返回undefined
    • Will throw if one of the operations throws or throw statement is used inside the withTransaction callback如果在withTransaction回调中使用了其中一个操作抛出或throw语句,将引发

    Checkout a descriptive example here:请在此查看描述性示例:

    see

    https://www.mongodb.com/developer/quickstart/node-transactions/

    Type parameters类型参数

    • T = void

    Parameters参数

    Returns 返回 Promise<undefined | Document>

    A raw command response or undefined原始命令响应或未定义

  • getEventListeners(emitter: EventEmitter | _DOMEventTarget, name: string | symbol): Function[]
  • 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,这与调用emitter上的.listeners完全相同。

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

    const { getEventListeners, EventEmitter } = require('events');

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

    v15.2.0, v14.17.0

    Parameters参数

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

    Returns 返回 Function[]

  • listenerCount(emitter: EventEmitter, eventName: string | symbol): number
  • A class method that returns the number of listeners for the given eventNameregistered on the given emitter.返回在给定emitter上注册的给定eventName的侦听器数量的类方法。

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

    v0.9.12

    deprecated

    Since v3.2.0 - Use listenerCount instead.自v3.2.0起-改用listenerCount

    Parameters参数

    • emitter: EventEmitter

      The emitter to query要查询的发射器

    • eventName: string | symbol

      The event name事件名称

    Returns 返回 number

  • on(emitter: EventEmitter, eventName: string, options?: StaticEventEmitterOptions): AsyncIterableIterator<any>
  • const { on, EventEmitter } = require('events');
    (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')) {
    // 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可用于取消等待事件:

    const { on, EventEmitter } = require('events');
    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 useif concurrent execution is required.如果需要并发执行,请不要使用。
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here此处无法访问
    })();

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

    v13.6.0, v12.16.0

    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事件

  • once(emitter: _NodeEventTarget, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise<any[]>
  • once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>
  • 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,当EventEmitter发出给定事件时,该Promise将被满足,或者当EventEmitter在等待时发出'error'时,该Promise被拒绝。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'

    const { once, EventEmitter } = require('events');

    async function run() {
    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.log('error happened', err);
    }
    }

    run();

    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'事件本身,则它将被视为任何其他类型的事件,无需特殊处理:

    const { EventEmitter, once } = require('events');

    const ee = new EventEmitter();

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

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

    // Prints: ok boom

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

    const { EventEmitter, once } = require('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!
    since

    v11.13.0, v10.16.0

    Parameters参数

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

    Returns 返回 Promise<any[]>

  • Parameters参数

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

    Returns 返回 Promise<any[]>

  • setMaxListeners(n?: number, ...eventTargets: (EventEmitter | _DOMEventTarget)[]): void
  • const { setMaxListeners, EventEmitter } = require('events');
    const target = new EventTarget();
    const emitter = new EventEmitter();
    setMaxListeners(5, target, emitter);
    since

    v15.4.0

    Parameters参数

    • Optional n: number

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

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

    Returns 返回 void

Generated using TypeDoc