繁体   English   中英

nodejs 不显示来自 mongodb 的数据

[英]nodejs doesn't display data from 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 Node\node_modules\mongodb\lib\cmap\connection_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 Node\node_modules\mongodb\lib\cmap\connection_pool.js:452:45)
    at ConnectionPool.close (e:\new Node\node_modules\mongodb\lib\cmap\connection_pool.js:260:14)
    at Server.destroy (e:\new Node\node_modules\mongodb\lib\sdam\server.js:128:21)
    at destroyServer (e:\new Node\node_modules\mongodb\lib\sdam\topology.js:445:12)
    at node:internal/util:361:7
    at new Promise (<anonymous>)
    at destroyServer (node:internal/util:347:12)
    at e:\new Node\node_modules\mongodb\lib\sdam\topology.js:226:56
    at Function.from (<anonymous>)
    at Topology.close (e:\new Node\node_modules\mongodb\lib\sdam\topology.js:225:40) {
  address: 'localhost:27017',
  [Symbol(errorLabels)]: Set(0) {}
}


所以这里的问题似乎是什么

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

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

此外,在collection有机会返回其结果之前同步关闭client ,这是异步发生的。 尝试以下操作:

collection.find().toArray().then((data) => {
  console.log(data);
  client.close();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM