Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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();
    });
  });
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda