2

I am trying to query MongoDB using NodeJS using the following piece of code.

mongoClient.connect(constants.mongo_url, { useNewUrlParser: true }, (err, database) => {
        if(err){
            console.log('Error occured while trying to connect to database');
            throw err;
        }
        var db = database.db(constants.ease_db);
        var results= db.collection(constants.products_collection).find({});

        response.send(JSON.stringify(results));
        database.close();
    });

However, the output generated is as follows -

{"pool":null,"server":null,"disconnectHandler":{"s":{"storedOps":[],"storeOptions":{"force":false,"bufferMaxEntries":-1},"topology":{"domain":null,"_events":{"error":[null,null],"timeout":[null,null],"close":[null,null],"parseError":[null,null],"open":[null,null],"fullsetup":[null,null],"all":[null,null],"reconnect":[null,null]},"_eventsCount":25,"_maxListeners":null,"clientInfo":{"driver":{"name":"nodejs","version":"3.1.10"},"os":{"type":"Windows_NT","name":"win32","architecture":"x64","version":"10.0.17134"},"platform":"Node.js v8.9.4, LE"},"s":{"coreTopology":{"domain":null,"_events":{},"_eventsCount":20,"id":0,"s":{"options":{"host":"localhost","port":27017,"disconnectHandler":"~disconnectHandler","reconnect":true,"emitError":true,"size":5,"monitorCommands":false,"socketTimeout":360000,"connectionTimeout":30000,"clientInfo":"~disconnectHandler~s~topology~clientInfo","servers":[{"host":"localhost","port":27017}],"caseTranslate":true,"useNewUrlParser":true,"db":"ease","authSource":"ease","dbName":"ease","socketTimeoutMS":360000,"connectTimeoutMS":30000,"bson":{}},"logger":{"className":"Server"},"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","pool":{"domain":null,"_events":{},"_eventsCount":10,"topology":"~disconnectHandler~s~topology~s~coreTopology","options":{"host":"localhost","port":27017,"size":5,"minSize":0,"connectionTimeout":30000,"socketTimeout":360000,"keepAlive":true,"keepAliveInitialDelay":300000,"noDelay":true,"ssl":false,"checkServerIdentity":true,"ca":null,"crl":null,"cert":null,"key":null,"passPhrase":null,"rejectUnauthorized":false,"promoteLongs":true,"promoteValues":true,"promoteBuffers":false,"reconnect":true,"reconnectInterval":1000,"reconnectTries":30,"domainsEnabled":false,"disconnectHandler":"~disconnectHandler","emitError":true,"monitorCommands":false,"clientInfo":"~disconnectHandler~s~topology~clientInfo","servers":"~disconnectHandler~s~topology~s~coreTopology~s~options~servers","caseTranslate":true,"useNewUrlParser":true,"db":"ease","authSource":"ease","dbName":"ease","socketTimeoutMS":360000,"connectTimeoutMS":30000,"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson"},"id":0,"retriesLeft":30,"reconnectId":null,"logger":{"className":"Pool"},"state":"connected","availableConnections":[{"id":0,"host":"localhost","port":27017}],"inUseConnections":[],"connectingConnections":[],"executing":false,"queue":[],"authProviders":{"mongocr":{"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","authStore":[]},"x509":{"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","authStore":[]},"plain":{"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","authStore":[]},"gssapi":{"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","authStore":[]},"sspi":{"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","authStore":[]},"scram-sha-1":{"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","authStore":[],"id":0,"cryptoMethod":"sha1"},"scram-sha-256":{"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","authStore":[],"id":1,"cryptoMethod":"sha256"}},"reconnectConnection":null,"authenticating":false,"loggingout":false,"nonAuthenticatedConnections":[],"authenticatingTimestamp":null,"numberOfConsecutiveTimeouts":0,"connectionIndex":1},"disconnectHandler":"~disconnectHandler","monitoring":true,"inTopology":false,"monitoringInterval":5000,"topologyId":-1,"compression":{"compressors":[]},"clusterTime":null,"serverDescription":{"topologyType":"Single","servers":[{"address":"localhost:27017","arbiters":[],"hosts":[],"passives":[],"type":"Standalone"}]},"topologyDescription":{"topologyType":"Unknown","servers":[{"address":"localhost:27017","arbiters":[],"hosts":[],"passives":[],"type":"Unknown"}]}},"ismaster":{"ismaster":true,"maxBsonObjectSize":16777216,"maxMessageSizeBytes":48000000,"maxWriteBatchSize":100000,"localTime":"2019-01-11T22:24:22.784Z","logicalSessionTimeoutMinutes":30,"minWireVersion":0,"maxWireVersion":7,"readOnly":false,"ok":1},"lastIsMasterMS":37,"monitoringProcessId":{"_called":false,"_idleTimeout":5000,"_idlePrev":{"_idleNext":"~disconnectHandler~s~topology~s~coreTopology~monitoringProcessId","_idlePrev":"~disconnectHandler~s~topology~s~coreTopology~monitoringProcessId","_timer":{"_list":"~disconnectHandler~s~topology~s~coreTopology~monitoringProcessId~_idlePrev"},"_unrefed":false,"msecs":5000,"nextTick":false},"_idleNext":"~disconnectHandler~s~topology~s~coreTopology~monitoringProcessId~_idlePrev","_idleStart":6025,"_repeat":null,"_destroyed":false},"initialConnect":false,"wireProtocolHandler":{},"_type":"server","clientInfo":{"driver":{"name":"nodejs","version":"3.1.10"},"os":{"type":"Windows_NT","name":"win32","architecture":"x64","version":"10.0.17134"},"platform":"Node.js v8.9.4, LE, mongodb-core: 3.1.9"},"lastUpdateTime":0,"lastWriteDate":0,"staleness":0},"sCapabilities":{"hasAggregationCursor":true,"hasWriteCommands":true,"hasTextSearch":true,"hasAuthCommands":true,"hasListCollectionsCommand":true,"hasListIndexesCommand":true,"minWireVersion":0,"maxWireVersion":7,"maxNumberOfDocsInBatch":100000,"commandsTakeWriteConcern":true,"commandsTakeCollation":true},"clonedOptions":"~disconnectHandler~s~topology~s~coreTopology~s~options","reconnect":true,"emitError":true,"poolSize":5,"storeOptions":"~disconnectHandler~s~storeOptions","store":"~disconnectHandler","host":"localhost","port":27017,"options":{"host":"localhost","port":27017,"disconnectHandler":"~disconnectHandler","reconnect":true,"emitError":true,"size":5,"monitorCommands":false,"socketTimeout":360000,"connectionTimeout":30000,"clientInfo":"~disconnectHandler~s~topology~clientInfo","servers":"~disconnectHandler~s~topology~s~coreTopology~s~options~servers","caseTranslate":true,"useNewUrlParser":true,"db":"ease","authSource":"ease","dbName":"ease","socketTimeoutMS":360000,"connectTimeoutMS":30000},"sessionPool":{"topology":"~disconnectHandler~s~topology~s~coreTopology","sessions":[]},"sessions":[]}}},"length":0},"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","ns":"ease.product_master","cmd":{"find":"ease.product_master","limit":0,"skip":0,"query":{},"hint":null,"slaveOk":false,"readPreference":null},"options":{"skip":0,"limit":0,"hint":null,"slaveOk":false,"readPreference":null,"db":{"domain":null,"_events":{},"_eventsCount":0,"s":{"databaseName":"ease","dbCache":{},"children":[],"topology":"~disconnectHandler~s~topology","options":{"authSource":"ease"},"logger":{"className":"Db"},"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","bufferMaxEntries":-1,"parentDb":null,"noListener":false},"serverConfig":"~disconnectHandler~s~topology","bufferMaxEntries":-1,"databaseName":"ease"},"disconnectHandler":"~disconnectHandler","topology":"~disconnectHandler~s~topology"},"topology":"~disconnectHandler~s~topology","cursorState":{"cursorId":null,"cmd":"~cmd","documents":[],"cursorIndex":0,"dead":false,"killed":false,"init":false,"notified":false,"limit":0,"skip":0,"batchSize":1000,"currentLimit":0,"reconnect":true},"logger":{"className":"Cursor"},"_readableState":{"objectMode":true,"highWaterMark":16,"buffer":{"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,"destroyed":false,"defaultEncoding":"utf8","awaitDrain":0,"readingMore":false,"decoder":null,"encoding":null},"readable":true,"domain":null,"_events":{},"_eventsCount":0,"s":{"numberOfRetries":5,"tailableRetryInterval":500,"currentNumberOfRetries":5,"state":0,"streamOptions":{},"bson":"~disconnectHandler~s~topology~s~coreTopology~s~options~bson","ns":"ease.product_master","cmd":"~cmd","options":"~options","topology":"~disconnectHandler~s~topology","topologyOptions":"~disconnectHandler~s~topology~s~coreTopology~s~options","currentDoc":null}}

I am not able to understand what is wrong. I've tried the basic way of querying MongoDB as directed by W3Schools. I did not find any thing over the internet similar to this issue. Please help!

mongo_url: "mongodb://localhost:27017/ease", ease_database: "ease", products_collection: "product_master"

1
  • In their API documentation, Ctrl-F lib/collection.js and you'll find an example doing exactly what you're trying to do. Commented Jan 11, 2019 at 22:47

2 Answers 2

4

Adding a .toArray() worked for me.

var results=db.collection(constants.products_collection).find({}).toArray();
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is with -

var results= db.collection(constants.products_collection).find({});

The way you're using it is synchronous while it is not. You should try -

db.collection(constants.products_collection).find({}).exec(function(err, data) {
    if (err) {
        // handle error here..
    } else {
        response.send(JSON.stringify(data));
        database.close();
    }
});

This allows your call to wait for results from query and then send the results through response.

2 Comments

Worked! Thanks.. :)
Glad, I could help. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.