Home > Mobile >  nodejs doesn't display data from mongodb
nodejs doesn't display data from mongodb

Time:11-27

hello i made a simple code that display all the documents on the collection here's my code

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 contains only one collection called tutorial and that collection only contains one document so it should display this

{
  "_id": {
    "$oid": "637bd20b45dc6d7d03eedb49"
  },
  "name": "Bahy",
  "email": "[email protected]",
  "password": "1234"
}

but in results i got this

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

so what seems to be the problem here i searched a lot but didn't get an answer

update: as a result for Heiko Theißen answer when i run it gives me this error

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


so what seems to be the problem here

CodePudding user response:

The callback function in MongoClient.connect takes only one argument, which is the client.

Therefore, in your function (err, client) => {...}, client is undefined and err is the client, which you log. The else branch in your code is never executed.

Also, you close the client synchronously, before the collection has a chance to return its result, which happens asynchronously. Try the following:

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