Не удается выполнить поиск $ в наборе реплик mongodb - PullRequest
0 голосов
/ 29 мая 2020

Я хочу получить сообщение из коллекции 'posts' с деталями пользователей, хранящихся в коллекции 'users'. Коллекция сообщений имеет ID в качестве (_id) userId коллекции пользователей. Я использовал $ lookup для извлечения данных из двух коллекций.

const data = await db.collection('posts').aggregate([ { $lookup: { from: "users", localField: "ID", foreignField: "_id", as: "det"}}]);

При использовании данных он возвращает объект AggregationCursor, как показано ниже

AggregationCursor {


 _readableState: ReadableState {
    objectMode: true,
    highWaterMark: 16,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: null,
    pipesCount: 0,
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    sync: true,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    emitClose: true,
    autoDestroy: false,
    destroyed: false,
    defaultEncoding: 'utf8',
    awaitDrain: 0,
    readingMore: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  readable: true,
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  operation: AggregateOperation {
    options: { readPreference: [ReadPreference] },
    ns: MongoDBNamespace { db: 'alumni-portal', collection: '$cmd' },
    readPreference: ReadPreference { mode: 'primary', tags: undefined },
    readConcern: undefined,
    writeConcern: undefined,
    explain: false,
    fullResponse: true,
    target: 'posts',
    pipeline: [ [Object] ],
    hasWriteStage: false,
    cursorState: {
      cursorId: null,
      cmd: {},
      documents: [],
      cursorIndex: 0,
      dead: false,
      killed: false,
      init: false,
      notified: false,
      limit: 0,
      skip: 0,
      batchSize: 1000,
      currentLimit: 0,
      transforms: undefined,
      raw: undefined
    }
  },
  pool: null,
  server: null,
  disconnectHandler: undefined,
  bson: BSON {},
  ns: 'alumni-portal.$cmd',
  namespace: MongoDBNamespace { db: 'alumni-portal', collection: '$cmd' },
  cmd: {},
  options: {
    readPreference: ReadPreference { mode: 'primary', tags: undefined }
  },
  topology: NativeTopology {
    _events: [Object: null prototype] {
      authenticated: [Function],
      error: [Array],
      timeout: [Array],
      close: [Array],
      parseError: [Array],
      fullsetup: [Array],
      all: [Array],
      reconnect: [Array],
      commandStarted: [Function],
      commandSucceeded: [Function],
      commandFailed: [Function],
      serverOpening: [Function],
      serverClosed: [Function],
      serverDescriptionChanged: [Function],
      serverHeartbeatStarted: [Function],
      serverHeartbeatSucceeded: [Function],
      serverHeartbeatFailed: [Function],
      topologyOpening: [Function],
      topologyClosed: [Function],
      topologyDescriptionChanged: [Function],
      joined: [Function],
      left: [Function],
      ping: [Function],
      ha: [Function],
      connectionPoolCreated: [Function],
      connectionPoolClosed: [Function],
      connectionCreated: [Function],
      connectionReady: [Function],
      connectionClosed: [Function],
      connectionCheckOutStarted: [Function],
      connectionCheckOutFailed: [Function],
      connectionCheckedOut: [Function],
      connectionCheckedIn: [Function],
      connectionPoolCleared: [Function],
      open: [Function]
    },
    _eventsCount: 35,
    _maxListeners: Infinity,
    s: {
      id: 0,
      options: [Object],
      seedlist: [Array],
      state: 'connected',
      description: [TopologyDescription],
      serverSelectionTimeoutMS: 30000,
      heartbeatFrequencyMS: 10000,
      minHeartbeatFrequencyMS: 500,
      Cursor: [Function: Cursor],
      bson: BSON {},
      servers: [Map],
      sessionPool: [ServerSessionPool],
      sessions: Set {},
      promiseLibrary: [Function: Promise],
      credentials: [MongoCredentials],
      clusterTime: [Object],
      connectionTimers: Set {},
      sCapabilities: [ServerCapabilities]
    },
    [Symbol(kCapture)]: false,
    [Symbol(waitQueue)]: Denque { _head: 3, _tail: 3, _capacityMask: 3, _list: [Array] }
  },
  cursorState: {
    cursorId: null,
    cmd: {},
    documents: [],
    cursorIndex: 0,
    dead: false,
    killed: false,
    init: false,
    notified: false,
    limit: 0,
    skip: 0,
    batchSize: 1000,
    currentLimit: 0,
    transforms: undefined,
    raw: undefined
  },
  logger: Logger { className: 'Cursor' },
  s: {
    numberOfRetries: 5,
    tailableRetryInterval: 500,
    currentNumberOfRetries: 5,
    state: 0,
    promiseLibrary: [Function: Promise],
    explicitlyIgnoreSession: false
  },
  [Symbol(kCapture)]: false
}

Но тот же код возвращает желаемый результат в mongoshell. Я не понимаю, почему data возвращает объект AggregationCursor. Заранее спасибо.

PS - Я использую набор реплик из 3 узлов.

1 Ответ

0 голосов
/ 31 мая 2020

Мне нужно только добавить .toArray () в конце оператора кода. Итак, ответ в приведенном выше коде должен быть таким, как показано ниже.

const data = await db.collection('posts').aggregate([ { $lookup: { from: "users", localField: "ID", foreignField: "_id", as: "det"}}]).toArray();
...