Home > front end >  Could not get mongodb connectivity with nodejs
Could not get mongodb connectivity with nodejs

Time:10-02

I have tried this in nodejs but i am getting undefined as output in my console

// Connect using a MongoClient instance
const MongoClient = require("mongodb").MongoClient;
const test = require("assert");
// Connection url
const url = "mongodb://localhost:27017";
// Database Name
const dbName = "test";
// Connect using MongoClient
const mongoClient = new MongoClient(url);
mongoClient.connect(function (err, client) {
  const db = client.db(dbName);
  try {
    db.collection("employeeDetails")
      .find({})
      .toArray(function (err, res) {
        console.log(res);
      });
  } catch (e) {
    console.log(e);
  } finally {
    client.close();
  }
});

I have data in mongodb : enter image description here

How do i get my employee details in my console Any help would be appreciated

CodePudding user response:

You're closing the connection before getting the results. If you print err inside toArray() along with result, you will see below error -

MongoExpiredSessionError: Cannot use a session that has ended

This is happening because the db.collection("employeeDetails")... is getting called but waits for results in callback, till then it moves ahead and since after that statement you are exiting try-catch, you enter into finally which closes the session. When the db.collection... call is processed, this session is already ended and you see this error.

You can use async await. Modify your code as below -

// Connect using a MongoClient instance
const MongoClient = require("mongodb").MongoClient;
const test = require("assert");
// Connection url
const url = "mongodb://localhost:27017";
// Database Name
const dbName = "test";
// Connect using MongoClient
const mongoClient = new MongoClient(url);
mongoClient.connect(async function (err, client) {
  const db = client.db(dbName);
  try {
    const result = await db.collection('employeeDetails').find({}).toArray();
    console.log(result);
  } catch (e) {
    console.log(e);
  } finally {
    client.close();
  }
});

In the line mongoClient.connect(async function (err, client).. we're using async before the callback function and later inside, we can just get the result using -

const result = await db.collection('employeeDetails').find({}).toArray();

After this console.log will print your results correctly.

CodePudding user response:

This works for me let result = await collection(collection).find(query).toArray()

  • Related