简体   繁体   中英

How can I get the aggregate search value using Mongoose from different Node.js?

I have this mongoose query to get some geoNear value.

   const results = await mongoose.connection.db
      .collection('placemodels')
      .aggregate([
        {
          $geoNear: {
            near: { type: 'Point', coordinates: [89.9741, 21.5112] },
            distanceField: 'calcDistance',
            maxDistance: 25000,
            spherical: true,
          },
        },
      ]);
    console.log(results);

However, I am receiving

AggregationCursor {
  _readableState: ReadableState {
    objectMode: true,
    highWaterMark: 16,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: [],
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    sync: true,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    destroyed: false,
    errored: false,
    closed: false,
    closeEmitted: false,
    defaultEncoding: 'utf8',
    awaitDrainWriters: null,
    multiAwaitDrain: false,
    readingMore: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  operation: AggregateOperation {
    options: { readPreference: [ReadPreference] },
    ns: MongoDBNamespace { db: 'test', collection: '$cmd' },
    readPreference: ReadPreference { mode: 'primary', tags: undefined },
    readConcern: undefined,
    writeConcern: WriteConcern { w: 'majority' },
    explain: false,
    fullResponse: true,
    target: 'placemodels',
    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: 'test.$cmd',
  namespace: MongoDBNamespace { db: 'test', collection: '$cmd' },
  cmd: {},
  options: {
    readPreference: ReadPreference { mode: 'primary', tags: undefined }
  },
  topology: NativeTopology {
    _events: [Object: null prototype] {
      topologyDescriptionChanged: [Array],
      authenticated: [Function (anonymous)],
      error: [Array],
      timeout: [Array],
      close: [Array],
      parseError: [Array],
      fullsetup: [Array],
      all: [Array],
      reconnect: [Array],
      commandStarted: [Function (anonymous)],
      commandSucceeded: [Function (anonymous)],
      commandFailed: [Function (anonymous)],
      serverOpening: [Function (anonymous)],
      serverClosed: [Function (anonymous)],
      serverDescriptionChanged: [Function (anonymous)],
      serverHeartbeatStarted: [Function (anonymous)],
      serverHeartbeatSucceeded: [Function (anonymous)],
      serverHeartbeatFailed: [Function (anonymous)],
      topologyOpening: [Function (anonymous)],
      topologyClosed: [Function (anonymous)],
      joined: [Array],
      left: [Function (anonymous)],
      ping: [Function (anonymous)],
      ha: [Function (anonymous)],
      connectionPoolCreated: [Function (anonymous)],
      connectionPoolClosed: [Function (anonymous)],
      connectionCreated: [Function (anonymous)],
      connectionReady: [Function (anonymous)],
      connectionClosed: [Function (anonymous)],
      connectionCheckOutStarted: [Function (anonymous)],
      connectionCheckOutFailed: [Function (anonymous)],
      connectionCheckedOut: [Function (anonymous)],
      connectionCheckedIn: [Function (anonymous)],
      connectionPoolCleared: [Function (anonymous)],
      open: [Function],
      reconnectFailed: [Function (anonymous)]
    },
    _eventsCount: 36,
    _maxListeners: Infinity,
    s: {
      id: 0,
      options: [Object],
      seedlist: [Array],
      state: 'connected',
      description: [TopologyDescription],
      serverSelectionTimeoutMS: 30000,
      heartbeatFrequencyMS: 10000,
      minHeartbeatFrequencyMS: 500,
      Cursor: [class Cursor extends CoreCursor],
      bson: BSON {},
      servers: [Map],
      sessionPool: [ServerSessionPool],
      sessions: Set(0) {},
      promiseLibrary: [Function: Promise],
      credentials: [MongoCredentials],
      clusterTime: [Object],
      connectionTimers: Set(0) {},
      srvPoller: [SrvPoller],
      detectTopologyDescriptionChange: [Function (anonymous)]
    },
    [Symbol(kCapture)]: false,
    [Symbol(waitQueue)]: Denque { _head: 0, _tail: 0, _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
}

this result?

I tried to use different queries like .find() and other stuff. Nothing seems to work. How can I get the value from aggregate search? I'd also tried to do query inside of the collection('model', (err, collections) => {---- HERE ----}) and it did not work :(

You need to consume the data from AggregationCursor . One way to do this is:

for (let doc = await results.next(); doc != null; doc = await results.next()) {
    console.log(doc);
    // process your aggregation result here
}

See the documentation for further details regarding Cursors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM