首页 > 解决方案 > 使用 NodeJS 查询 MongoDB 时出现问题

问题描述

我正在尝试使用以下代码使用 NodeJS 查询 MongoDB。

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();
    });

但是,生成的输出如下 -

{"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}}

我无法理解出了什么问题。我已经按照 W3Schools 的指示尝试了查询 MongoDB 的基本方法。我没有在互联网上找到任何与此问题类似的东西。请帮忙!

mongo_url:“mongodb://localhost:27017/ease”,ease_database:“ease”,products_collection:“product_master”

标签: node.jsmongodb

解决方案


问题在于——

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

您使用它的方式是同步的,而它不是。你应该试试 -

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

这允许您的呼叫等待查询结果,然后通过响应发送结果。


推荐阅读