nodejs 不显示来自 MongoDB 的数据



你好,我做了一个简单的代码,显示集合上的所有文档,这是我的代码

const mongodb = require("mongodb");
const express = require("express");
var app = express();
var mongoClient = mongodb.MongoClient;
var conn = "mongodb://localhost:27017";
mongoClient.connect(conn).then((err, client) => {
if (err) {
console.log(err);
} else {
console.log("connection established");
var db = client.db("mydb");
var collection = db.collection("tutorial");
collection
.find()
.toArray()
.then((data) => {
console.log(data);
});
client.close();
}
});
app.listen(3000, () => {
console.log("Server started");
});

mydb只包含一个名为tutorial的集合,并且该集合只包含一个文档,因此它应该显示这个

{
"_id": {
"$oid": "637bd20b45dc6d7d03eedb49"
},
"name": "Bahy",
"email": "bahy@gmail.com",
"password": "1234"
}

但是在结果中我得到了这个

<ref *1> MongoClient {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: {
url: 'mongodb://localhost:27017',
bsonOptions: {
raw: false,
promoteLongs: true,
promoteValues: true,
promoteBuffers: false,
ignoreUndefined: false,
bsonRegExp: false,
serializeFunctions: false,
fieldsAsRaw: {},
enableUtf8Validation: true
},
namespace: MongoDBNamespace { db: 'admin', collection: undefined },
hasBeenClosed: false,
sessionPool: ServerSessionPool { client: [Circular *1], sessions: [List] },
activeSessions: Set(0) {},
options: [Getter],
readConcern: [Getter],
writeConcern: [Getter],
readPreference: [Getter],
logger: [Getter],
isMongoClient: [Getter]
},
topology: Topology {
_events: [Object: null prototype] {
connectionPoolCreated: [Function (anonymous)],
connectionPoolReady: [Function (anonymous)],
connectionPoolCleared: [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)],
commandStarted: [Function (anonymous)],
commandSucceeded: [Function (anonymous)],
commandFailed: [Function (anonymous)],
serverOpening: [Function (anonymous)],
serverClosed: [Function (anonymous)],
serverDescriptionChanged: [Function (anonymous)],
topologyOpening: [Function (anonymous)],
topologyClosed: [Function (anonymous)],
topologyDescriptionChanged: [Function (anonymous)],
error: [Function (anonymous)],
timeout: [Function (anonymous)],
close: [Function (anonymous)],
serverHeartbeatStarted: [Function (anonymous)],
serverHeartbeatSucceeded: [Function (anonymous)],
serverHeartbeatFailed: [Function (anonymous)]
},
_eventsCount: 26,
_maxListeners: undefined,
selectServerAsync: [Function (anonymous)],
bson: [Object: null prototype] {
serialize: [Function: serialize],
deserialize: [Function: deserialize]
},
s: {
id: 0,
options: [Object: null prototype],
seedlist: [Array],
state: 'connected',
description: [TopologyDescription],
serverSelectionTimeoutMS: 30000,
heartbeatFrequencyMS: 10000,
minHeartbeatFrequencyMS: 500,
servers: [Map],
credentials: undefined,
clusterTime: undefined,
connectionTimers: Set(0) {},
detectShardedTopology: [Function: detectShardedTopology],
detectSrvRecords: [Function: detectSrvRecords]
},
client: [Circular *1],
[Symbol(kCapture)]: false,
[Symbol(waitQueue)]: List { count: 0, head: [Object] }
},
[Symbol(kCapture)]: false,
[Symbol(options)]: [Object: null prototype] {
hosts: [ new HostAddress('localhost:27017') ],
compressors: [ 'none' ],
connectTimeoutMS: 30000,
directConnection: false,
metadata: {
driver: [Object],
os: [Object],
platform: 'Node.js v16.17.0, LE (unified)|Node.js v16.17.0, LE (unified)'
},
enableUtf8Validation: true,
forceServerObjectId: false,
heartbeatFrequencyMS: 10000,
keepAlive: true,
keepAliveInitialDelay: 120000,
loadBalanced: false,
localThresholdMS: 15,
logger: Logger { className: 'MongoClient' },
maxConnecting: 2,
maxIdleTimeMS: 0,
maxPoolSize: 100,
minPoolSize: 0,
minHeartbeatFrequencyMS: 500,
monitorCommands: false,
noDelay: true,
pkFactory: { createPk: [Function: createPk] },
raw: false,
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined,
maxStalenessSeconds: undefined,
minWireVersion: undefined
},
retryReads: true,
retryWrites: true,
serverSelectionTimeoutMS: 30000,
socketTimeoutMS: 0,
srvMaxHosts: 0,
srvServiceName: 'mongodb',
waitQueueTimeoutMS: 0,
zlibCompressionLevel: 0,
dbName: 'test',
userSpecifiedAuthSource: false,
userSpecifiedReplicaSet: false
}
}

所以这里的问题似乎是我搜索了很多,但没有得到答案

更新:因此,当我运行Heiko Theißen答案时,它会给我这个错误

Error: 
e:new Nodenode_modulesmongodblibcmapconnection_pool.js:452
const error = this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this);
^
PoolClosedError [MongoPoolClosedError]: Attempted to check out a connection from closed connection pool
at ConnectionPool.processWaitQueue (e:new Nodenode_modulesmongodblibcmapconnection_pool.js:452:45)
at ConnectionPool.close (e:new Nodenode_modulesmongodblibcmapconnection_pool.js:260:14)
at Server.destroy (e:new Nodenode_modulesmongodblibsdamserver.js:128:21)
at destroyServer (e:new Nodenode_modulesmongodblibsdamtopology.js:445:12)
at node:internal/util:361:7
at new Promise (<anonymous>)
at destroyServer (node:internal/util:347:12)
at e:new Nodenode_modulesmongodblibsdamtopology.js:226:56
at Function.from (<anonymous>)
at Topology.close (e:new Nodenode_modulesmongodblibsdamtopology.js:225:40) {
address: 'localhost:27017',
[Symbol(errorLabels)]: Set(0) {}
}

那么这里的问题是什么

MongoClient.connect中的回调函数只接受一个参数,即客户端。

因此,在您的函数(err, client) => {...}中,client是未定义的,err是您记录的客户端。代码中的else分支永远不会执行。

同样,在collection有机会返回结果之前,同步关闭client,这是异步发生的。试试以下命令:
collection.find().toArray().then((data) => {
console.log(data);
client.close();
});

最新更新