Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!