dsomel21
dsomel21

Reputation: 626

Doing a proper MongoDB Query (TypeError: Converting circular structure to JSON)

I am querying something that I have done multiple times. Take a look, I can't seem to understand.

/* GET all things */
app.get('/things', function(req, res) {
    var search = req.query.search;
    console.log(search); //works properly and prints strings
    Thing.find({ name: {$regex : search}}, function(err, val) {
        if(err) throw error;
        console.log(val); // returns some horrible JSON
        res.send(JSON.stringify(val)); // Throws TypeError
    });
})

I thought maybe my query was wrong and that perhaps maybe it's the Mongo shell throwing issues, but when I went into the Mongo shell.

use dbname

> db.booking.find({name: {$regex: "G"}})

>{ "_id" : ObjectId("58238283565e2c1940b16d48"), "name" : "Go to Lesters"}

This is what happens when I print val.

Readable {
  pool: null,
  server: null,
  disconnectHandler: 
   { s: { storedOps: [], storeOptions: [Object], topology: [Object] },
     length: [Getter] },
  bson: {},
  ns: 'vectio.booking',
  cmd: 
   { find: 'vectio.booking',
     limit: 0,
     skip: 0,
     query: { name: [Object] },
     slaveOk: true,
     readPreference: { preference: 'primary', tags: undefined, options: [Object] } },
  options: 
   { skip: 0,
     limit: 0,
     raw: undefined,
     hint: null,
     timeout: undefined,
     slaveOk: true,
     readPreference: { preference: 'primary', tags: undefined, options: [Object] },
     db: 
      EventEmitter {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        s: [Object],
        serverConfig: [Getter],
        bufferMaxEntries: [Getter],
        databaseName: [Getter] },
     promiseLibrary: [Function: Promise],
     disconnectHandler: { s: [Object], length: [Getter] } },
  topology: 
   EventEmitter {
     domain: null,
     _events: 
      { reconnect: [Function],
        reconnectFailed: [Function],
        timeout: [Object],
        error: [Object],
        close: [Function],
        destroy: [Object],
        serverDescriptionChanged: [Function],
        serverHeartbeatStarted: [Function],
        serverHeartbeatSucceeded: [Function],
        serverHeartbeatFailed: [Function],
        serverOpening: [Function],
        serverClosed: [Function],
        topologyOpening: [Function],
        topologyClosed: [Function],
        topologyDescriptionChanged: [Function],
        attemptReconnect: [Function],
        monitoring: [Function] },
     _eventsCount: 17,
     _maxListeners: undefined,
     id: 0,
     s: 
      { options: [Object],
        logger: [Object],
        Cursor: [Object],
        bson: {},
        pool: [Object],
        disconnectHandler: [Object],
        monitoring: true,
        inTopology: false,
        monitoringInterval: 5000,
        topologyId: -1 },
     ismaster: 
      { ismaster: true,
        maxBsonObjectSize: 16777216,
        maxMessageSizeBytes: 48000000,
        maxWriteBatchSize: 1000,
        localTime: 2016-11-09T20:41:56.152Z,
        maxWireVersion: 2,
        minWireVersion: 0,
        ok: 1 },
     lastIsMasterMS: 6,
     monitoringProcessId: 
      Timeout {
        _called: false,
        _idleTimeout: 5000,
        _idlePrev: [Object],
        _idleNext: [Object],
        _idleStart: 255,
        _onTimeout: [Function],
        _repeat: null },
     initalConnect: false,
     wireProtocolHandler: {},
     _type: 'server',
     clientInfo: 
      { driver: [Object],
        os: [Object],
        platform: 'Node.js v6.2.1, LE, mongodb-core: 2.0.13' },
     lastUpdateTime: 0,
     lastWriteDate: 0,
     staleness: 0 },
  cursorState: 
   { cursorId: null,
     cmd: 
      { find: 'vectio.booking',
        limit: 0,
        skip: 0,
        query: [Object],
        slaveOk: true,
        readPreference: [Object] },
     documents: [],
     cursorIndex: 0,
     dead: false,
     killed: false,
     init: false,
     notified: false,
     limit: 0,
     skip: 0,
     batchSize: 1000,
     currentLimit: 0,
     transforms: undefined },
  logger: { className: 'Cursor' },
  _readableState: 
   ReadableState {
     objectMode: true,
     highWaterMark: 16,
     buffer: [],
     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: {},
     ns: 'vectio.booking',
     cmd: 
      { find: 'vectio.booking',
        limit: 0,
        skip: 0,
        query: [Object],
        slaveOk: true,
        readPreference: [Object] },
     options: 
      { skip: 0,
        limit: 0,
        raw: undefined,
        hint: null,
        timeout: undefined,
        slaveOk: true,
        readPreference: [Object],
        db: [Object],
        promiseLibrary: [Function: Promise],
        disconnectHandler: [Object] },
     topology: 
      EventEmitter {
        domain: null,
        _events: [Object],
        _eventsCount: 17,
        _maxListeners: undefined,
        id: 0,
        s: [Object],
        ismaster: [Object],
        lastIsMasterMS: 6,
        monitoringProcessId: [Object],
        initalConnect: false,
        wireProtocolHandler: {},
        _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: {},
        clientInfo: [Object],
        readPreference: [Object],
        promiseLibrary: [Function: Promise],
        bson: {} },
     promiseLibrary: [Function: Promise],
     currentDoc: null },
  sortValue: undefined }
/home/dilraj/Documents/Vectio/scenario-dilraj/node_modules/mongodb/lib/utils.js:99
    process.nextTick(function() { throw err; });
                                  ^

TypeError: Converting circular structure to JSON

I am trying to get something like { _id: ObjectId("58238283565e2c1940b16d48"), name: "Go to Lesters" }

or something similar, as long as it makes sense! I just haven't seen anything like this.

I am using Node's Express JS framework, and the only modules I have are Nodemon, Express, bodyParser and Mongo. Nothing else! Thank you, appreciate the love!

Upvotes: 5

Views: 8176

Answers (3)

Vikash Kumar Gaurav
Vikash Kumar Gaurav

Reputation: 1

You can use the same syntax but you need to handle the promise using .then or use async await

Upvotes: -1

Chris Hartwig
Chris Hartwig

Reputation: 86

If you request returns a single object, you can also use Thing.findOne({ name: {$regex : search}}, function(err, val) {

Upvotes: 1

AdamExchange
AdamExchange

Reputation: 1301

The object you are logging is the Mongo cursor. This can be useful at times but to just get the document that is not what you need.

Thing.find(query).toArray(function(err, result){ ... })

Should just return the documents that match your query.

Upvotes: 5

Related Questions