Cannot retrieve all entries from MongoDB collection

i’m trying to retrieve all entires from mongo yet I keep on getting an error that I couldn’t find any while having there are some entries.

const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'toy_db';

tryMongo();

function tryMongo() {
  MongoClient.connect(url, (err, client) => {
    if (err) return console.log('Cannot connect to DB');
    console.log('Connected successfully to server');
    const db = client.db(dbName);
    const collection = db.collection('toy');
    collection.find().toArray((err, docs) => {
      if (err) return console.log('cannot find toys');
      console.log('found these:');
      console.log(docs);
    });
    client.close();
  });
}

this is the error i’m getting : Server listening on port 3030! Connected successfully to server cannot find toys

I have also added a picture of mongo enter image description here

appreciating any kind of help!

Answer

You are closing mongo connection before you get response from server. Move client.close(); inside toArray callback.

const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'toy_db';

tryMongo();

function tryMongo() {
  MongoClient.connect(url, (err, client) => {
    if (err) return console.log(err);
    console.log('Connected successfully to server');
    const db = client.db(dbName);
    const collection = db.collection('toy');
    collection.find().toArray((err, docs) => {
      if (err) {
        console.log(err);
      } else {
        console.log('found these:');
        console.log(docs);
      }
      client.close();
    });
  });
}
Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .