Options
All
  • Public
  • Public/Protected
  • All
Menu

Class FindCursor<TSchema>

Type parameters

  • TSchema = any

Hierarchy继承层级

Index索引

Events事件

CLOSE: "close" = ...

Properties属性

captureRejectionSymbol: typeof captureRejectionSymbol
captureRejections: boolean

Sets or gets the default captureRejection value for all emitters.

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 closed(): boolean
  • get id(): undefined | Long
  • get killed(): boolean
  • get loadBalanced(): boolean

Methods方法

  • [asyncIterator](): AsyncIterator<TSchema, void, undefined>
  • addCursorFlag(flag: "tailable" | "oplogReplay" | "noCursorTimeout" | "awaitData" | "exhaust" | "partial", value: boolean): FindCursor<TSchema>
  • Add a cursor flag to the cursor

    Parameters参数

    • flag: "tailable" | "oplogReplay" | "noCursorTimeout" | "awaitData" | "exhaust" | "partial"

      The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.要设置的标志必须是以下标志之一:['tailable''oplogReplay''noCursorTimeout''awaitData''partial'-。

    • value: boolean

      The flag boolean value.标志布尔值。

    Returns 返回 FindCursor<TSchema>

  • addQueryModifier(name: string, value: string | number | boolean | Document): FindCursor<TSchema>
  • Add a query modifier to the cursor query

    Parameters参数

    • name: string

      The query modifier (must start with $, such as $orderby etc)查询修饰符(必须以$开头,如$orderby等)

    • value: string | number | boolean | Document

      The modifier value.修改器值。

    Returns 返回 FindCursor<TSchema>

  • allowDiskUse(allow?: boolean): FindCursor<TSchema>
  • bufferedCount(): number
  • Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance返回此游标的新的未初始化副本,其选项与当前实例上设置的选项相匹配

    Returns 返回 FindCursor<TSchema>

  • Set the collation options for the cursor.设置游标的排序规则选项。

    Parameters参数

    • value: CollationOptions

      The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).更新操作的游标排序选项(MongoDB 3.4或更高版本)设置(有关可用字段,请参阅3.4文档)。

    Returns 返回 FindCursor<TSchema>

  • Add a comment to the cursor query allowing for tracking the comment in the log.向游标查询添加注释,以便跟踪日志中的注释。

    Parameters参数

    • value: string

      The comment attached to this query.附加到此查询的注释。

    Returns 返回 FindCursor<TSchema>

  • Get the count of documents for this cursor获取此游标的文档数

    deprecated

    Use collection.estimatedDocumentCount or collection.countDocuments instead

    Returns 返回 Promise<number>

  • deprecated

    Use collection.estimatedDocumentCount or collection.countDocuments instead. Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • deprecated

    Use collection.estimatedDocumentCount or collection.countDocuments instead.

    Parameters参数

    Returns 返回 Promise<number>

  • deprecated

    Use collection.estimatedDocumentCount or collection.countDocuments instead. 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<AbstractCursorEvents[EventKey]>): boolean
  • eventNames(): string[]
  • forEach(iterator: (doc: TSchema) => boolean | void): Promise<void>
  • forEach(iterator: (doc: TSchema) => boolean | void, callback: Callback<void>): void
  • Iterates over all the documents for this cursor using the iterator, callback pattern.使用迭代器回调模式迭代此游标的所有文档。

    If the iterator returns false, iteration will stop.如果迭代器返回false,迭代将停止。

    Parameters参数

    • iterator: (doc: TSchema) => boolean | void

      The iteration callback.迭代回调。

        • (doc: TSchema): boolean | void
        • Parameters参数

          • doc: TSchema

          Returns 返回 boolean | void

    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参数

    • iterator: (doc: TSchema) => boolean | void
        • (doc: TSchema): boolean | void
        • Parameters参数

          • doc: TSchema

          Returns 返回 boolean | void

    • callback: Callback<void>

    Returns 返回 void

  • getMaxListeners(): number
  • hasNext(): Promise<boolean>
  • hasNext(callback: Callback<boolean>): void
  • Set the cursor hint设置游标提示

    Parameters参数

    • hint: Hint

      If specified, then the query system will only consider plans using the hinted index.如果指定,查询系统将只考虑使用提示索引的计划。

    Returns 返回 FindCursor<TSchema>

  • Set the limit for the cursor.设置游标的限制。

    Parameters参数

    • value: number

      The limit for the cursor query.游标查询的限制。

    Returns 返回 FindCursor<TSchema>

  • listenerCount<EventKey>(type: string | symbol | EventKey): number
  • map<T>(transform: (doc: TSchema) => T): FindCursor<T>
  • Map all documents using the provided function If there is a transform set on the cursor, that will be called first and the result passed to this function's transform.使用提供的函数映射所有文档如果游标上有一个转换集,则首先调用该转换集,并将结果传递给该函数的转换。

    remarks

    Note for Typescript Users:Typescript用户注意事项: adding a transform changes the return type of the iteration of this cursor, it does not return a new instance of a cursor. 添加转换会更改此游标迭代的返回类型,它不会返回游标的新实例。This means when calling map, you should always assign the result to a new variable in order to get a correctly typed cursor variable. 这意味着在调用map时,您应该始终将结果分配给一个新变量,以便获得正确类型的游标变量。Take note of the following example:请注意以下示例:

    Type parameters类型参数

    • T

    Parameters参数

    • transform: (doc: TSchema) => T
        • (doc: TSchema): T
        • Parameters参数

          • doc: TSchema

          Returns 返回 T

    Returns 返回 FindCursor<T>

  • Set the cursor max设置游标最大值

    Parameters参数

    • max: Document

      Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). 指定$max值以指定特定索引的独占上限,以约束find()的结果。The $max specifies the upper bound for all keys of a specific index in order.$max按顺序指定特定索引的所有键的上限。

    Returns 返回 FindCursor<TSchema>

  • maxAwaitTimeMS(value: number): FindCursor<TSchema>
  • Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)在尾游标查询上设置maxAwaitTimeMS,以允许自定义选项awaitData的超时值(仅在MongoDB 3.2或更高版本上支持,否则将忽略)

    Parameters参数

    • value: number

      Number of milliseconds to wait before aborting the tailed query.中止尾查询之前等待的毫秒数。

    Returns 返回 FindCursor<TSchema>

  • Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)在游标查询上设置maxTimeMS,允许查询的硬超时限制(仅在MongoDB 2.6或更高版本上支持)

    Parameters参数

    • value: number

      Number of milliseconds to wait before aborting the query.中止查询之前等待的毫秒数。

    Returns 返回 FindCursor<TSchema>

  • Set the cursor min设置游标最小值

    Parameters参数

    • min: Document

      Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). 指定$min值以指定特定索引的包含下限,以约束find()的结果。The $min specifies the lower bound for all keys of a specific index in order.$min按顺序指定特定索引的所有键的下限。

    Returns 返回 FindCursor<TSchema>

  • next(): Promise<null | TSchema>
  • next(callback: Callback<null | TSchema>): void
  • next(callback?: Callback<null | TSchema>): void | Promise<null | TSchema>
  • Get the next available document from the cursor, returns null if no more documents are available.从游标获取下一个可用文档,如果没有更多可用文档,则返回null

    Returns 返回 Promise<null | TSchema>

  • deprecated

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

    Parameters参数

    Returns 返回 void

  • deprecated

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

    Parameters参数

    • Optional callback: Callback<null | TSchema>

    Returns 返回 void | Promise<null | TSchema>

  • Add a project stage to the aggregation pipeline将项目阶段添加到聚合管道

    remarks

    In order to strictly type this function you must provide an interface that represents the effect of your projection on the result documents.为了严格地键入此函数,您必须提供一个表示投影对结果文档的影响的接口。

    By default chaining a projection to your cursor changes the returned type to the generic Document type. 默认情况下,将投影链接到游标会将返回的类型更改为通用Document类型。You should specify a parameterized type to have assertions on your final results.您应该指定一个参数化类型,以便对最终结果进行断言。

    example
    // Best way
    const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
    // Flexible way
    const docs: FindCursor<Document> = cursor.project({ _id: 0, a: true });
    remarks

    Note for Typescript Users:Typescript用户注意事项: adding a transform changes the return type of the iteration of this cursor, it does not return a new instance of a cursor. 添加转换会更改此游标迭代的返回类型,它不会返回游标的新实例。This means when calling project, you should always assign the result to a new variable in order to get a correctly typed cursor variable. 这意味着在调用项目时,您应该始终将结果分配给一个新变量,以便获得正确类型的游标变量。Take note of the following example:请注意以下示例:

    example
    const cursor: FindCursor<{ a: number; b: string }> = coll.find();
    const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
    const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();

    // or always use chaining and save the final cursor或始终使用链接并保存最终游标

    const cursor = coll.find().project<{ a: string }>({
    _id: 0,
    a: { $convert: { input: '$a', to: 'string' }
    }});

    Type parameters类型参数

    Parameters参数

    Returns 返回 FindCursor<T>

  • readBufferedDocuments(number?: number): TSchema[]
  • removeAllListeners<EventKey>(event?: string | symbol | EventKey): FindCursor<TSchema>
  • Set the cursor returnKey. 设置游标returnKey。If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. 如果设置为true,则修改游标以仅返回查询结果的索引字段,而不是文档。If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields.如果设置为true且查询不使用索引执行读取操作,则返回的文档将不包含任何字段。

    Parameters参数

    • value: boolean

      the returnKey value.returnKey值。

    Returns 返回 FindCursor<TSchema>

  • rewind(): void
  • Rewind this cursor to its uninitialized state. 将此游标回放到其未初始化状态。Any options that are present on the cursor will remain in effect. 游标上的任何选项都将保持有效。Iterating this cursor will cause new queries to be sent to the server, even if the resultant data has already been retrieved by this cursor.迭代此游标将导致向服务器发送新的查询,即使此游标已经检索到结果数据。

    Returns 返回 void

  • showRecordId(value: boolean): FindCursor<TSchema>
  • Modifies the output of a query by adding a field $recordId to matching documents. 通过向匹配的文档添加字段$recordId来修改查询的输出。$recordId is the internal key which uniquely identifies a document in a collection.$recordId是唯一标识集合中文档的内部密钥。

    Parameters参数

    • value: boolean

      The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc选项现已被弃用,并替换为showRecordId字段。$showDiskLoc will still be accepted for OP_QUERY stye find.$showDiskLoc仍将接受OP_QUERY类型查找。

    Returns 返回 FindCursor<TSchema>

  • Set the skip for the cursor.设置游标的跳过。

    Parameters参数

    • value: number

      The skip for the cursor query.游标查询的跳过。

    Returns 返回 FindCursor<TSchema>

  • Sets the sort order of the cursor query.设置游标查询的排序顺序。

    Parameters参数

    • sort: Sort

      The key or keys set for the sort.为排序设置的一个或多个键。

    • Optional direction: SortDirection

      The direction of the sorting (1 or -1).排序方向(1或-1)。

    Returns 返回 FindCursor<TSchema>

  • toArray(): Promise<TSchema[]>
  • toArray(callback: Callback<TSchema[]>): void
  • Returns an array of documents. 返回文档数组。The caller is responsible for making sure that there is enough memory to store the results. Note that the array only contains partial results when this cursor had been previously accessed. 调用者负责确保有足够的内存来存储结果。请注意,当该游标以前被访问时,数组只包含部分结果。In that case, cursor.rewind() can be used to reset the cursor.在这种情况下,可以使用cursor.rewind()重置游标。

    Returns 返回 Promise<TSchema[]>

  • deprecated

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

    Parameters参数

    Returns 返回 void

  • tryNext(): Promise<null | TSchema>
  • tryNext(callback: Callback<null | TSchema>): void
  • 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