在mongoDb中的选择返回奇怪的东西

时间:2017-11-06 20:04:26

标签: node.js mongodb

我有以下选择查询:

student.findCourses = (fcallback) => {
    global.db.collection('students').find(({}, { "courses.courseName": true, _id: false }), (err, result) => {

        if (err) {
            var jError = { "status": "error", "message": "ERROR -> student.js -> 001" }
            console.log(jError)
            return fcallback(true, jError)
        }
        var jOk = { "status": "ok", "message": "student.js -> found -> 000" }
        console.log(jOk)
        console.log(result);
        return fcallback(false, jOk)
    })
}

这就是我在控制台中获得的内容。我的状态还不错,但对我来说这似乎很奇怪。

{ status: 'ok', message: 'student.js -> found -> 000' }
Cursor {
  pool: null,
  server: null,
  disconnectHandler:
   Store {
     s: { storedOps: [], storeOptions: [Object], topology: [Object] },
     length: [Getter] },
  bson: BSON {},
  ns: 'kea.students',
  cmd:
   { find: 'kea.students',
     limit: 0,
     skip: 0,
     query: { 'courses.courseName': true, _id: false },
     readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
     slaveOk: true },
  options:
   { readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
     skip: 0,
     limit: 0,
     raw: undefined,
     hint: null,
     timeout: undefined,
     slaveOk: true,
     db:
      Db {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        s: [Object],
        serverConfig: [Getter],
        bufferMaxEntries: [Getter],
        databaseName: [Getter] },
     promiseLibrary: [Function: Promise],
     disconnectHandler: Store { s: [Object], length: [Getter] } },
  topology:
   Server {
     domain: null,
     _events:
      { reconnect: [Function: reconnectHandler],
        reconnectFailed: [Function: reconnectFailedHandler],
        serverDescriptionChanged: [Function],
        serverHeartbeatStarted: [Function],
        serverHeartbeatSucceeded: [Function],
        serverHeartbeatFailed: [Function],
        serverOpening: [Function],
        serverClosed: [Function],
        topologyOpening: [Function],
        topologyClosed: [Function],
        topologyDescriptionChanged: [Function],
        attemptReconnect: [Function],
        monitoring: [Function],
        timeout: [Function],
        error: [Object],
        close: [Function],
        destroy: [Function: destroyHandler] },
     _eventsCount: 17,
     _maxListeners: undefined,
     id: 0,
     s:
      { options: [Object],
        logger: [Object],
        Cursor: [Object],
        bson: BSON {},
        pool: [Object],
        disconnectHandler: [Object],
        monitoring: true,
        inTopology: false,
        monitoringInterval: 5000,
        topologyId: -1,
        serverDescription: [Object],
        topologyDescription: [Object] },
     ismaster:
      { ismaster: true,
        maxBsonObjectSize: 16777216,
        maxMessageSizeBytes: 48000000,
        maxWriteBatchSize: 1000,
        localTime: 2017-11-06T19:51:35.856Z,
        maxWireVersion: 5,
        minWireVersion: 0,
        readOnly: false,
        ok: 1 },
     lastIsMasterMS: 10,
     monitoringProcessId:
      Timeout {
        _called: false,
        _idleTimeout: 5000,
        _idlePrev: [Object],
        _idleNext: [Object],
        _idleStart: 657,
        _onTimeout: [Function],
        _timerArgs: undefined,
        _repeat: null },
     initalConnect: false,
     wireProtocolHandler: WireProtocol { legacyWireProtocol: WireProtocol {} },
     _type: 'server',
     clientInfo:
      { driver: [Object],
        os: [Object],
        platform: 'Node.js v6.11.4, LE, mongodb-core: 2.1.17' },
     lastUpdateTime: 0,
     lastWriteDate: 0,
     staleness: 0 },
  cursorState:
   { cursorId: null,
     cmd:
      { find: 'kea.students',
        limit: 0,
        skip: 0,
        query: [Object],
        readPreference: [Object],
        slaveOk: true },
     documents: [],
     cursorIndex: 0,
     dead: false,
     killed: false,
     init: false,
     notified: false,
     limit: 0,
     skip: 0,
     batchSize: 1000,
     currentLimit: 0,
     transforms: undefined },
  logger: Logger { className: 'Cursor' },
  _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,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  s:
   { numberOfRetries: 5,
     tailableRetryInterval: 500,
     currentNumberOfRetries: 5,
     state: 0,
     streamOptions: {},
     bson: BSON {},
     ns: 'kea.students',
     cmd:
      { find: 'kea.students',
        limit: 0,
        skip: 0,
        query: [Object],
        readPreference: [Object],
        slaveOk: true },
     options:
      { readPreference: [Object],
        skip: 0,
        limit: 0,
        raw: undefined,
        hint: null,
        timeout: undefined,
        slaveOk: true,
        db: [Object],
        promiseLibrary: [Function: Promise],
        disconnectHandler: [Object] },
     topology:
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 17,
        _maxListeners: undefined,
        id: 0,
        s: [Object],
        ismaster: [Object],
        lastIsMasterMS: 10,
        monitoringProcessId: [Object],
        initalConnect: false,
        wireProtocolHandler: [Object],
        _type: 'server',
        clientInfo: [Object],
        lastUpdateTime: 0,
        lastWriteDate: 0,
        staleness: 0 },
     topologyOptions:
      { host: 'localhost',
        port: 27017,
        disconnectHandler: [Object],
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        socketOptions: {},
        socketTimeout: 360000,
        connectionTimeout: 30000,
        clientInfo: [Object],
        readPreference: [Object],
        promiseLibrary: [Function: Promise],
        bson: BSON {} },
     promiseLibrary: [Function: Promise],
     currentDoc: null },
  sortValue: undefined }

    at Module.load (module.js:487:32)

我想只获取查询中的数据,如下所示:

{ "courses": [
                {
                    "courseName": "Web-development"
                },

                {
                    "courseName": "Databases"
                },
                {
                    "courseName": "Interface-Design"

                }
            ]
        }

我不确定我的查询或我要求结果的方式是否有问题?

当我确实插入时,我说的是console.log(JSON.stringify(result.ops)),它只给我插入的数据,但是如果我用它来进行选择它会给我未定义。

这就是为什么我不确定查询是否真的有效,或者您只是以不同的方式询问获取所选数据的原因?

1 个答案:

答案 0 :(得分:1)

来自文档。 find返回一个光标

https://docs.mongodb.com/manual/reference/method/db.collection.find/

这是您在console

中看到的内容

为了获得结果,您可以使用toArray https://docs.mongodb.com/manual/reference/method/cursor.toArray/

global.db.collection('students')
 .find(({}, { "courses.courseName": 1, _id: 0}).toArray()
 .then((data) => {//you will have your result here})
 .catch(err => {//error if something wrong});

或以旧方式

global.db.collection('students')
 .find(({}, { "courses.courseName": 1, _id: 0})
 .toArray((err,data) => {//do stuff here});

希望这有帮助。