Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

appreciating any kind of help!

>Solution :

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();
    });
  });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading