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

164
Vistas
Get data from MongoDB

I'm trying to load data from MongoDB to my express to eventually show in my html with use of angular. Now I've got it working to get the data, but this only works with one record in the database. If i create multiple records, it gives the following error in the console:

"can't send headers after they are sent"

This is my "get" request in express:

router.get('/getdata', function(req, res, next){
var findDocuments = function(db, callback) {
var cursor = db.collection('userdata').find({});
cursor.each(function(err, doc) {
  assert.equal(err, null);
  if (doc != null) {
     res.status(200).json(doc);
  } else {
     callback();
  }
});
};
  mongo.connect(url, function(err, db) {
   assert.equal(null, err);
  findDocuments(db, function() {
    db.close();
  });
});
  console.log('Items have been returned');
});
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

router.get('/getdata', function(req, res, next){

  var findDocuments = function(db, callback) {

    //use such codtion that filter null/empty doc
    //replace key with field of your doc
    var cursor = db.collection('userdata').find({'key' : {$exists : true}});

    //return all docs
     if(cursor){
    return callback(cursor);
    }else{
    return callback([]);
       }

  };

  mongo.connect(url, function(err, db) {
   assert.equal(null, err);
   findDocuments(db, function(docs) {
    db.close();

    //send finaly doc here 
    console.log(docs);
    res.status(200).send(docs);

  });
 });

  console.log('Items have been returned');
});
about 4 years ago · Santiago Trujillo 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