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');
});
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');
});